python twisted应用_您如何通过Python(而不是通过Twisted)运行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)

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

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

python chatserver.py

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

Thanks.

解决方案

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)

you can do:

from twisted.internet import reactor

reactor.listenTCP(1025, factory)

reactor.run()

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)

Hope it helps!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值