将参数传递给twisted工厂以传递给会话
我写了一个基于 twisted sshsimpleserver.py 的 sshdaemon,运行得很好。
http://twistedmatrix.com/documents/current/conch/examples/
不过我现在想给 EchoProtocol 传一个命令行参数,这样可以根据这个参数改变它的行为。 我该怎么做呢?在这种情况下,我想把 'options.test' 参数传给我的协议。
[...]
if __name__ == '__main__':
parser = optparse.OptionParser()
parser.add_option('-p', '--port', action = 'store', type = 'int',
dest = 'port', default = 1235, help = 'server port')
parser.add_option('-t', '--test', action = 'store', type =
'string', dest = 'test', default = '123')
(options, args) = parser.parse_args()
components.registerAdapter(ExampleSession, ExampleAvatar,
session.ISession)
[...]
reactor.listenTCP(options.port, ExampleFactory())
reactor.run()
因为会话实例是由工厂创建的,所以我似乎无法把额外的参数传给会话构造函数或协议。 我已经尝试把 options 名称设为全局变量,但在协议的上下文中看不到它。
顺便说一下,我把协议类移动到了自己的文件里,并在主文件中导入了它。
1 个回答
4
你可以自己创建一个工厂,并给它传递参数。下面是一个来自文档的例子。
from twisted.internet.protocol import Factory, Protocol
from twisted.internet.endpoints import TCP4ServerEndpoint
from twisted.internet import reactor
class QOTD(Protocol):
def connectionMade(self):
# self.factory was set by the factory's default buildProtocol:
self.transport.write(self.factory.quote + '\r\n')
self.transport.loseConnection()
class QOTDFactory(Factory):
# This will be used by the default buildProtocol to create new protocols:
protocol = QOTD
def __init__(self, quote=None):
self.quote = quote or 'An apple a day keeps the doctor away'
endpoint = TCP4ServerEndpoint(reactor, 8007)
endpoint.listen(QOTDFactory("configurable quote"))
reactor.run()