Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
607 views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...