我正在通过学习Twisted的方式进行工作,偶然发现了我不确定我非常喜欢的东西-“ Twisted Command Prompt”。我在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 Command Prompt”(运行以下命令,并通过以下命令来运行它:
twistd -y chatserver.py
有什么方法可以更改代码(设置Twisted配置设置等),以便我可以通过以下方式简单地运行它:
python chatserver.py
我已经用Google搜索,但是搜索字词似乎太含糊,无法返回任何有意义的回复。
谢谢。
我不知道这是否是最好的方法,但我要做的不是:
application = service.Application("chatserver")
internet.TCPServer(1025, factory).setServiceParent(application)
您可以做:
from twisted.internet import reactor
reactor.listenTCP(1025, factory)
reactor.run()
总结,如果您想拥有两个选项(扭曲和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)
希望有帮助!
不要将“扭曲”与“ twistd
”混淆。当您使用“ twistd
”时,您使用Python运行程序。 “ twistd
”是一个Python程序,除其他外,它可以从.tac
文件加载应用程序(如您在此处所做的那样。)>“ Twisted Command Prompt”是Twisted安装程序提供的便利,可以帮助Windows上的人们。它所做的只是将%PATH%
设置为包含包含“ twistd
”程序的目录。如果正确设置%PATH%或使用完整路径调用它,则可以从普通命令提示符下运行扭曲。
如果您对此不满意,也许您可以扩展您的问题,以包括使用“ twistd
”时遇到的问题的描述。
例如,我使用:
runfileserver.bat:
C:\program_files\python26\Scripts\twistd.py -y C:\source\python\twisted\fileserver.tac
我没有用过扭曲的自我。但是,您可以尝试查看twisted是否为python文件本身。我猜想它只是在设法从正确的路径加载适当的扭曲库。我已在Windows上针对Flask网站成功使用了简单的Twisted Web服务器。其他人也可以在Windows上成功使用Twisted来验证该配置吗?
new_app.py if __name__ == "__main__": reactor_args = {} def run_twisted_wsgi(): from twisted.internet import reactor from twisted.web.server import Site from twisted.web.wsgi import WSGIResource resource = WSGIResource(reactor, reactor.getThreadPool(), app) site = Site(resource) reactor.listenTCP(5000, site) reactor.run(**reactor_args) if app.debug: # Disable twisted signal handlers in development only. reactor_args['installSignalHandlers'] = 0 # Turn on auto reload. import werkzeug.serving run_twisted_wsgi = werkzeug.serving.run_with_reloader(run_twisted_wsgi) run_twisted_wsgi() old_app.py if __name__ == "__main__": app.run()