扭曲工厂的时滞

2024-09-28 21:55:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我不知道如何在twisted.internet.ClientFactory中使用twisted.internet.loopingCall()之类的东西

我需要编写python脚本来扫描目录中有电话号码的传入文件,读取它们,并使用使用twisted库的YATEyaypmpython模块进行调用。在

client_factory = yaypm.TCPDispatcherFactory(start_client)
reactor.connectTCP(host, port, client_factory)
reactor.run()

其中yaypm.TCPDispatcherFactory派生自twisted.internet.ClientFactory和{}是连接成功后将执行的函数。在

如果start_client只进行演示调用:

^{pr2}$

一切都好。在

dialer是实现yaypm.flow逻辑的对象,完整描述放在http://docs.yate.ro/wiki/YAYPM:Bridge_and_then_unbridge中)

我需要在start_client中写这样的东西

d = dialer(client_yate)
files = os.listdir(input_directory)
for filename in files:
    <read caller and target numbers from file>
    d.call(caller, target)
    time.sleep(interval)

我知道在主线程中使用sleep函数会导致死锁。 我应该如何实现上面的算法?在


Tags: and函数clientfactorytwistedfilesstartinternet
1条回答
网友
1楼 · 发布于 2024-09-28 21:55:24

如果与inlineCallbacks修饰符一起使用,^{}的行为类似于sleep()调用。下面是一个使用ClientFactory的简化示例:

from twisted.internet import reactor, task
from twisted.internet.defer import inlineCallbacks
from twisted.internet.protocol import Protocol, ClientFactory


class DoNothing(Protocol):
    def __init__(self, connection_callback):
        self.connection_callback = connection_callback

    def connectionMade(self):
        self.connection_callback()
        return


class ConnectionClientFactory(ClientFactory):
    def __init__(self, connection_callback):
        self.connection_callback = connection_callback

    def buildProtocol(self, addr):
        return DoNothing(self.connection_callback)



def sleep(delay):
    # Returns a deferred that calls do-nothing function
    # after `delay` seconds
    return task.deferLater(reactor, delay, lambda: None)


@inlineCallbacks
def repeat_forever(message):
    while True:
        print(message)
        yield sleep(1)


if __name__ == '__main__':
    repeat_forever('running')

    factory = ConnectionClientFactory(lambda: repeat_forever('connected'))
    reactor.connectTCP('example.com', 80, factory)
    reactor.run()

上面的代码本质上就是库对传入的回调所做的操作。如您所见,对repeat_forever('running')的调用与客户端连接后调用的调用同时运行。在

相关问题 更多 >