Twisted application without a twist

I wrote an application using the Twisted framework for myself. I run it with a command, for example:

twistd -y myapp.py --pidfile=/var/run/myapp.pid --logfile=/var/run/myapp.log 

It works fine =)

To run the application, I wrote a script with this command because I'm lazy ^^ But since I run my application with the same twistd parameter and I use the script shell solution is ugly, how can I do the same thing, but inside my application ? I would like to run the application simply by running ./myapp and without a shell.

I tried to find it in a twisted documentation and while reading a curved source, but I do not understand it, since this is my first Python application (wonderful btw language!)

Thanks in advance for any help.

+5
python twisted daemon
source share
2 answers

You need to import the twistd script as a module from Twisted and call it. The simplest solution to this, using an existing command line, would be to import the sys module instead of the argv command line, so that it looks like you want twistd work, and then run it.

Here is a simple script example that will take an existing command line and run it using 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 neatly merge this into a package, rather than hard-coded 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 this:

 #!/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 things like this to compute the corresponding pidfile and logfile paths.

A more complete solution is to write a twistd . The axiomatic command-line program from the Axiom object database project serves as a proven, worthy example of how to perform twistd command-line twistd with what is described above, but with more complex processing of command-line parameters, various functions that are not launched by twistd, and etc.

+6
source share

You can also create / config options for the twisted command and pass it to the twisted runner.

 #!/usr/bin/env python3 import twisted.scripts.twistd import twisted.scripts._twistd_unix config = twisted.scripts._twistd_unix.ServerOptions() config.parseOptions([ "--nodaemon", "web", "--listen=tcp:80", "--path=/some/path" ]) twisted.scripts._twistd_unix.UnixApplicationRunner(config).run() 
0
source share

All Articles