您需要将twistd 脚本作为模块从Twisted 导入并调用它。最简单的解决方案是使用您现有的命令行,导入 sys 模块以替换 argv 命令行,使其看起来像您希望 twistd 运行的方式,然后运行它。
这是一个简单的示例脚本,它将采用您现有的命令行并使用 Python 脚本而不是 shell 脚本运行它:
#!/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()
如果您想将其很好地捆绑到一个包中而不是硬编码路径中,您可以通过查看 Python 在每个模块中设置的特殊 __file__ 变量来确定 myapp.py 的路径。将其添加到示例中如下所示:
#!/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()
你显然可以做类似的事情来计算适当的 pidfile 和 logfile 路径。
更全面的解决方案是为twistd 编写a plugin。 Axiom 对象数据库项目中的axiomatic 命令行程序是一个经过测试的、值得生产的示例,说明如何对twistd 进行与上述类似的命令行操作,但更全面地处理命令-line 选项,不同的非 twistd 运行的实用程序功能,等等。