5

我已经编写了一个基于扭曲的 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()

由于会话实例是由工厂创建的,我似乎无法将额外的参数传递给会话构造函数和协议。我已经尝试将选项名称设为全局,但它在协议上下文/范围中不可见。

顺便提一句。我将协议类移动到它自己的文件中并将其导入到主文件中。

4

1 回答 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()
于 2013-02-15T13:40:03.010 回答