您如何通过Python(而不是通过Twisted)运行Twisted应用程序? [英] How do you you run a Twisted application via Python (instead of via Twisted)?

查看:168
本文介绍了您如何通过Python(而不是通过Twisted)运行Twisted应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Twisted,并且偶然发现了我不确定我非常喜欢的东西-"Twisted Command Prompt".我在Windows机器上摆弄Twisted,并尝试运行聊天"示例:

I am working my way through learning Twisted, and have stumbled across something I'm not sure I'm terribly fond of - the "Twisted Command Prompt". I am fiddling around with Twisted on my Windows machine, and tried running the "Chat" example:

from twisted.protocols import basic

class MyChat(basic.LineReceiver):
    def connectionMade(self):
        print "Got new client!"
        self.factory.clients.append(self)

    def connectionLost(self, reason):
        print "Lost a client!"
        self.factory.clients.remove(self)

    def lineReceived(self, line):
        print "received", repr(line)
        for c in self.factory.clients:
            c.message(line)

    def message(self, message):
        self.transport.write(message + '\n')


from twisted.internet import protocol
from twisted.application import service, internet

factory = protocol.ServerFactory()
factory.protocol = MyChat
factory.clients = []

application = service.Application("chatserver")
internet.TCPServer(1025, factory).setServiceParent(application)

但是,要将此应用程序作为Twisted服务器运行,我必须通过"Twisted Command Prompt"(运行命令提示符)并使用以下命令来运行它:

However, to run this application as a Twisted server, I have to run it via the "Twisted Command Prompt", with the command:

twistd -y chatserver.py

有什么方法可以更改代码(设置Twisted配置设置等),以便我可以通过以下方式简单地运行它:

Is there any way to change the code (set Twisted configuration settings, etc) so that I can simply run it via:

python chatserver.py

我已经搜索过Google,但是搜索字词似乎过于模糊,无法返回任何有意义的回复.

I've Googled, but the search terms seem to be too vague to return any meaningful responses.

谢谢.

推荐答案

我不知道这是否是最好的方法,但我要做的是:

I don't know if it's the best way to do this but what I do is instead of:

application = service.Application("chatserver")
internet.TCPServer(1025, factory).setServiceParent(application)

您可以这样做:

from twisted.internet import reactor
reactor.listenTCP(1025, factory)
reactor.run()

概述了您是否想要两个选项(扭曲和python):

Sumarized if you want to have the two options (twistd and python):

if __name__ == '__main__':
    from twisted.internet import reactor
    reactor.listenTCP(1025, factory)
    reactor.run()
else:
    application = service.Application("chatserver")
    internet.TCPServer(1025, factory).setServiceParent(application)

希望有帮助!

这篇关于您如何通过Python(而不是通过Twisted)运行Twisted应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆