如何通过Python运行Twisted应用程序(而不是通过Twisted)?

20 投票
6 回答
10493 浏览
提问于 2025-04-15 16:58

我正在学习Twisted这个框架,但遇到了一些我不太喜欢的东西——“Twisted命令提示符”。我在Windows电脑上玩Twisted,尝试运行一个“聊天”示例:

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命令提示符”来执行,命令是:

twistd -y chatserver.py

有没有办法修改代码(设置Twisted的配置等),这样我就可以直接通过:

python chatserver.py

来运行它呢?我在网上搜索过,但搜索的关键词似乎太模糊,没找到有用的答案。

谢谢。

6 个回答

2

也许你可以试试 run 或者 runApp 这两个在 twisted.scripts.twistd 模块里的方法。要是有用的话,麻烦告诉我一下,知道了会很高兴的!

14

不要把“Twisted”和“twistd”搞混了。当你使用“twistd”的时候,你实际上是在用Python运行一个程序。“twistd”是一个Python程序,它可以做很多事情,其中之一就是从一个.tac文件加载应用程序(就像你现在在做的那样)。

“Twisted命令提示符”是Twisted安装时提供的一个方便工具,主要是为了帮助Windows用户。它的作用就是把%PATH%设置为包含“twistd”程序的目录。如果你正确设置了%PATH%,或者用完整路径调用它,你也可以在普通的命令提示符下运行twistd。

如果你对这个解释不满意,也许你可以详细描述一下你在使用“twistd”时遇到的问题,这样大家可以更好地帮助你。

24

我不知道这是不是最好的方法,但我通常是这样做的,别直接用:

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

你可以这样做:

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

简单来说,如果你想同时使用这两种选项(twistd和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)

希望这对你有帮助!

撰写回答