Twisted application without twistd

☆樱花仙子☆ 提交于 2019-12-01 05:43:14

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.

You can also create the options / config for a 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()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!