Подтвердить что ты не робот

Как написать плагин Twisted client

Я использовал 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()

Я использовал ту же иерархию папок, о которой упоминалось в документации. Поскольку я не смог найти достаточно примеров плагинов в Интернете, я действительно застрял на этом этапе. Буду признателен за любую помощь. Может ли кто-нибудь сказать мне, как изменить код? Заранее благодарю вас.

4b9b3361

Ответ 2

Вы должны вернуть основной объект службы из вашего метода MyServiceMaker().makeService. Попробуйте добавить from twisted.internet import service, затем в makeService добавить это в начале: top_service = service.Multiservice() Создайте службу TCPServer: tcp_service = TCPServer(...) Добавьте его в верхнюю службу: tcp_service.setServiceParent(top_service) Затем верните верхнюю службу: return top_service

Вам также может потребоваться ознакомиться с этой замечательной серией обучающих программ из Dave Peticolas (статья № 16 - это полезная для вашей проблемы)

Ответ 3

Просто следуйте этим ссылкам для документации и справки:

twistedmatrix - docs

twisted.readthedocs.io -docs

from __future__ import print_function

from twisted.internet import reactor
from twisted.web.client import Agent
from twisted.web.http_headers import Headers

agent = Agent(reactor)

d = agent.request(
    'GET',
    'http://example.com/',
    Headers({'User-Agent': ['Twisted Web Client Example']}),
    None)

def cbResponse(ignored):
    print('Response received')
d.addCallback(cbResponse)

def cbShutdown(ignored):
    reactor.stop()
d.addBoth(cbShutdown)

reactor.run()

Вывод:

C:\Python27>python.exe twist001.py
Response received