我已经编写了一个基于扭曲的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',type =
'string',dest = 'test',default = '123')
(options,args) = parser.parse_args()
components.registerAdapter(ExampleSession,ExampleAvatar,session.ISession)
[...]
reactor.listenTCP(options.port,ExampleFactory())
reactor.run()
由于会话实例是由工厂创建的,我似乎无法做到
能够将其他args传递给会话构造函数和协议.
我已经尝试将选项名称设置为全局,但它在协议上下文/范围中不可见.
最佳答案
您可以创建自己的Factory并将参数传递给它.请参阅docs中的示例
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()