TwistD-使用Service.Application与选项允许参数解析



我想将服务器作为应用程序运行。为此,我有一个MyServer(name, port, host, testMode=False)类(从DatagramProtocol对象继承)。

在另一个文件中,我创建了一些命令来创建并启动我的服务器。或多或少,它看起来像:

from twisted.application import service, internet
name, port, host = #read from database
server = MyServer(name, port, host)
udp_server = internet.UDPServer(port, server)
application = service.Application("MyServer")
udp_server.setServiceParent(application)

name, porthost我从数据库中读取。我以'twistd -y my_server_run.py'启动服务器,一切都完美。

但是,我希望能够启动我的服务器进入模式:测试模式和标准模式。因此,我想将我从命令行中读取的参数作为参数作为一个参数。我找到了这些信息,我无法将它们解析为sys.argv,但是我必须实现usage.Options,因此我按照以下方式进行操作:

from twisted.application import service, internet
from twisted.python import usage
class Options(usage.Options):
    optParameters = [["test", "t", False, "The client test mode"]]

options = Options()
name, port, host = #read from database
try:
    options.parseOptions()
    server = MyServer(name, port, host, testMode=options['test'])
    udp_server = internet.UDPServer(port, server)
    application = service.Application("MyServer")
    udp_server.setServiceParent(application)

然后,我将服务器运行为:

'twistd -y run_client.py --test True'

但是,我遇到了错误:

option -y not recognized
Unhandled Error
out: Traceback (most recent call last):
out:   File "/usr/local/lib/python2.7/dist-packages/twisted/application/app.py", line 648, in run
out:     runApp(config)
out:   File "/usr/local/lib/python2.7/dist-packages/twisted/scripts/twistd.py", line 25, in runApp
out:     _SomeApplicationRunner(config).run()
out:   File "/usr/local/lib/python2.7/dist-packages/twisted/application/app.py", line 379, in run
out:     self.application = self.createOrGetApplication()
out:   File "/usr/local/lib/python2.7/dist-packages/twisted/application/app.py", line 444, in createOrGetApplication
out:     application = getApplication(self.config, passphrase)
out: --- <exception caught here> ---
out:   File "/usr/local/lib/python2.7/dist-packages/twisted/application/app.py", line 455, in getApplication
out:     application = service.loadApplication(filename, style, passphrase)
out:   File "/usr/local/lib/python2.7/dist-packages/twisted/application/service.py", line 411, in loadApplication
out:     passphrase)
out:   File "/usr/local/lib/python2.7/dist-packages/twisted/persisted/sob.py", line 224, in loadValueFromFile
out:     value = d[variable]
out: exceptions.KeyError: 'application'
out: Failed to load application: 'application'
out: Could not find 'application' in the file. To use 'twistd -y', your .tac

我找不到我在做什么错。任何建议都会非常有帮助。

不幸的是,service.Application不能与usage.Options一起使用,如此问题所讨论的。

如果您通过

启动服务器,可以使用选项
python run_client.py --test True

或使用扭曲插件(点击文件)。

您使用扭曲的应用程序配置文件,假设您在此文件中配置了服务器,并且它将作为生产系统上的服务启动。因此,可以将选项存储在某些配置文件或数据库中并在启动过程中读取它们是可以的。

相关内容

  • 没有找到相关文章