2013-02-13 81 views
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() 

因爲會話實例是由工廠創建,我似乎無法給 能夠通過額外的參數既不會話構造,也不是協議。 我已經嘗試使選項名稱爲全局但它在協議上下文/範圍中不可見。

Btw。我將協議類移入它自己的文件並將其導入到主文件中。

回答

4

您可以創建自己的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() 
+0

感謝您的示例和指針,這是一個很好的起點。不幸的是,該協議是在ExampleSession中創建的,但是它可以通過protocol.session.conn.transport.factory.quote進行訪問。 – Fabian 2013-02-19 11:54:27

+0

在openShell調用中,我們可以通過serverProtocol = ServerProtocol(CommandRecvLine,self,quote)將報價轉發給CommandRecvLine, – Fabian 2013-02-19 13:47:44