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

、私はセッションのコンストラクタやプロトコルのいずれにも追加の引数を渡すことができる に見えることはできません。 私は既にオプション名をglobalにしようとしましたが、プロトコルコンテキスト/スコープでは表示されません。

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

+0

openShellコールでは、次に、serverProtocol = ServerProtocol(CommandRecvLine、self、quote)を介してCommandRecvLineに引用を転送することができます。 – Fabian

関連する問題