Я использовал twisted
для реализации клиента. Он работает нормально. Теперь я хочу иметь возможность передавать ему аргументы командной строки, поэтому мне нужно реализовать плагин twisted
. Я выполнил множество поисков, чтобы найти ресурсы, которые покажут, как преобразовать программу в плагин. Однако я не мог найти то, что искал.
Вот связанная часть моего кода client.py
:
import sys
import time
import os
import errno
import re
from stat import *
global runPath
runPath = '/home/a02/Desktop/'
from twisted.python import log
from GlobalVariables import *
from twisted.internet import reactor, threads, endpoints
from time import sleep
from twisted.internet.protocol import ClientFactory# , Protocol
from twisted.protocols import basic
import copy
class MyChat(basic.LineReceiver):
def connectionMade(self):
print "Connected to the server!"
EchoClientFactory.buildClientObject(self.factory, self)
self.runPythonCommands = RunPythonCommands ()
return
def connectionLost(self, reason):
print "Lost Connection With Server!"
#self.factory.clients.remove(self)
#self.transport.loseConnection()
print 'connection aborted!'
#reactor.callFromThread(reactor.stop)
reactor.stop ()
return
def lineReceived(self, line):
#print "received", repr(line)
line = line.strip ()
if line == "EOF":
print "Test Completed"
self.factory.getLastReceivedMsg (line)
exeResult = self.runPythonCommands.runPythonCommand(line.strip())
self.sendLine(exeResult)
EchoClientFactory.lastReceivedMessage = ""
EchoClientFactory.clientObject[0].receivedMessages = []
return
def message (self, line):
self.sendLine(line)
#print line
return
class EchoClientFactory(ClientFactory):
protocol = MyChat
clientObject = []
lastReceivedMessage = ''
def buildClientObject (self, newClient):
client = Client ()
self.clientObject.append(client)
self.clientObject[0].objectProtocolInstance = newClient
return
def getLastReceivedMsg (self, message):
self.lastReceivedMessage = message
self.clientObject [0].lastReceivedMsg = message
self.clientObject[0].receivedMessages.append (message)
return
def connectionLost (self):
reactor.stop()
return
def clientConnectionFailed(self, connector, reason):
print 'Connection failed. Reason:', reason
connector.connect ()
return
Вот что я написал для моего client_plugin.py
:
from zope.interface import implements
from twisted.python import usage
from twisted.plugin import IPlugin
from twisted.application.service import IServiceMaker
from twisted.application.internet import TCPServer
from twisted.spread import pb
from slave.client import EchoClientFactory,MyChat, Client, RunPythonCommands, MyError, line
class Options(usage.Options):
optParameters = [["port", "p", 8789, "The port number to listen on."], ["host", "h", "192.168.47.187", "The host to connect to"]]
class MyServiceMaker(object):
implements(IServiceMaker, IPlugin)
tapname = "echoclient"
description = "Echo Client"
options = Options
def makeService(self, options):
clientfactory = pb.PBServerFactory(EchoClientFactory ())
return TCPServer(options["host"],int(options["port"]), clientfactory)
serviceMaker = MyServiceMaker()
Я использовал ту же иерархию папок, о которой упоминалось в документации. Поскольку я не смог найти достаточно примеров плагинов в Интернете, я действительно застрял на этом этапе. Буду признателен за любую помощь. Может ли кто-нибудь сказать мне, как изменить код? Заранее благодарю вас.