Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twisted application without twistd

I've wrote a nice app for myself using the Twisted framework. I launch it using a command like:

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

It works great =)

To launch my app I wrote a script with this command because I'm lazy^^ But since I launch my app with the same twistd option, and I tink the script shell solution is ugly, how I can do the same but inside my app? I'd like to launch my app by just doing ./myapp and without a shell work around.

I've tried to search about it in twisted documentation and by reading twisted source but I don't understand it since it's my first app in Python (wonderful language btw!)

Thanks in advance for anyhelp.

like image 592
unpythonicguy Avatar asked Jul 07 '11 12:07

unpythonicguy


1 Answers

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.

like image 86
Glyph Avatar answered Oct 23 '22 08:10

Glyph