问题描述
我使用Twisted框架为自己编写了一个不错的应用程序。我使用以下命令启动它:
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
效果很好=)
要启动我的应用程序,我用这个命令编写了一个脚本,因为我很懒^^
但是由于我使用相同的扭曲选项启动了我的应用程序,所以我修改了脚本shell解决方案很丑陋,但是如何在我的应用程序内部执行同样的操作?我想通过做 ./ myapp
来启动我的应用程序,而无需使用shell。
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曾尝试在扭曲的文档中以及通过阅读扭曲的源代码来搜索它,但由于它是我的第一个Python应用程序(很棒的语言btw!),我不理解它。
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.
推荐答案
您需要导入 twistd
脚本作为来自Twisted的模块,并调用它。使用现有命令行的最简单解决方案是导入 sys
模块以替换 argv
命令行,如下所示: twistd 运行,然后运行它。
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.
这是一个简单的示例脚本它将使用您现有的命令行并使用Python脚本而不是Shell脚本运行它:
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()
如果您想将其很好地捆绑成一个包而不是硬编码的路径,可以通过查看每个模块中Python设置的特殊 __ file __
变量来确定 myapp.py
的路径。将其添加到示例中看起来像这样:
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()
您显然可以做类似的事情来计算适当的pidfile和日志文件路径。
and you could obviously do similar things to compute appropriate pidfile and logfile paths.
更全面的解决方案是编写,用于扭曲
。 Axiom对象数据库项目中的axiomatic命令行程序是一个经过测试的,有价值的示例,说明如何对 twistd
进行类似的命令行操作上面介绍了什么,但是对命令行选项进行了更全面的处理,提供了不同的非扭转运行实用程序功能,等等。
这篇关于扭曲应用而无扭曲的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!