Twisted application without twistd
You need to import the twistd
script as a module from Twisted and invoke it. The simplest solution for this, using your existing command-line, would be to import the sys
module to replace the argv
command line to look like how you want twistd
to run, and then run it.
Here's a simple example script that will take your existing command-line and run it with a Python script instead of a shell script:
#!/usr/bin/python
from twisted.scripts.twistd import run
from sys import argv
argv[1:] = [
'-y', 'myapp.py',
'--pidfile', '/var/run/myapp.pid',
'--logfile', '/var/run/myapp.log'
]
run()
If you want to bundle this up nicely into a package rather than hard-coding paths, you can determine the path to myapp.py
by looking at the special __file__
variable set by Python in each module. Adding this to the example looks like so:
#!/usr/bin/python
from twisted.scripts.twistd import run
from my.application import some_module
from os.path import join, dirname
from sys import argv
argv[1:] = [
'-y', join(dirname(some_module.__file__), "myapp.py"),
'--pidfile', '/var/run/myapp.pid',
'--logfile', '/var/run/myapp.log'
]
run()
and you could obviously do similar things to compute appropriate pidfile and logfile paths.
A more comprehensive solution is to write a plugin for twistd
. The axiomatic command-line program from the Axiom object-database project serves as a tested, production-worthy example of how to do similar command-line manipulation of twistd
to what is described above, but with more comprehensive handling of command-line options, different non-twistd-running utility functionality, and so on.