哪一种Python库异步会是最适合我的code? Asyncore?扭曲? [英] Which Python async library would be best suited for my code? Asyncore? Twisted?

查看:217
本文介绍了哪一种Python库异步会是最适合我的code? Asyncore?扭曲?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序我工作将从两个网络资源同时阅读。我想尝试一个异步的方法,而不是使用线程。这导致了我想知道用哪个库...

I have a program I'm working on that will be reading from two 'network sources' simultaneously. I wanted to try out an asynchronous approach rather than use threading. This has lead me to wonder which library to use...

我已经想出一些简单的例子code之类的证明就是我的程序会做:

I've come up with some simple example code that kind of demonstrates what my program will be doing:

import sniffer

def first():
    for station in sniffer.sniff_wifi():
        log(station.mac())

def second():
    for station in sniffer.sniff_ethernet():
        log(station.mac())

first()
second()

两个嗅探器方法看起来有点像这样:

The two sniffer methods look somewhat like this:

def sniff_wifi(self):

    while True:
        yield mac_address

,而真循环显然使得它们阻塞。

The while True loop obviously makes them blocking.

我想用 asyncore 这个,因为它是标准库的一部分。任何第三方的依赖是一个奖金。但是,这并不意味着,如果你建议我这样做,我不会用它...

I want to use asyncore for this as it is part of the standard library. No 3rd party dependencies are a bonus. However, that doesn't mean I won't use it if you recommend I do...

我可以实现我想要与asyncore办?如果是这样,你能告诉我如何转换我的例子code到'asyncore code'?你知道什么好的asyncore教程?

Can I achieve what I'm trying to do with asyncore? If so, could you show me how to convert my example code to 'asyncore code'? Do you know of any good asyncore tutorials?

推荐答案

扭曲是pretty多的百般好。它更轻便,更加有特色,更简单,更具可扩展性,更好的维护,更好的记录,它可以做出美味煎蛋。 Asyncore,对于所有意图和目的,已经过时了。

Twisted is better in pretty much every possible way. It's more portable, more featureful, simpler, more scalable, better maintained, better documented, and it can make a delicious omelette. Asyncore is, for all intents and purposes, obsolete.

这是很难证明其中Twisted是在很短的答案(卓越的所有方法我怎么可能表现出的 HTTP / dns键入 /的ssh /的 SMTP / POP / IMAP / IRC / XMPP / <一个href=\"http://twistedmatrix.com/documents/10.2.0/api/twisted.internet.interfaces.IReactorProcess.html\">process-spawning/multi-threading ?在很短的示例服务器),所以不是我将重点介绍,人们似乎对扭曲的最常见的误解之一:它的某种程度上更复杂或难度比asyncore使用

It's hard to demonstrate all the ways in which Twisted is superior in a short answer (how could I demonstrate a http/dns/ssh/smtp/pop/imap/irc/xmpp/process-spawning/multi-threading server in a short example?), so instead I'll focus on one of the most common misconceptions that people seem to have about Twisted: that it's somehow more complex or harder to use than asyncore.

让我们先从一个asyncore例子。为了避免偏颇presentation,我将使用从别人谁仍然喜欢asyncore一点的例子。下面是理查德·琼斯博客采取(与省略为简洁起见评论)一个简单的例子asyncore

Let's start with an asyncore example. In order to avoid a biased presentation, I'll use an example from someone else who still likes asyncore a bit. Here's a simple asyncore example taken from Richard Jones' weblog (with comments elided for brevity).

首先,这里的服务器:

import asyncore, socket

class Server(asyncore.dispatcher):
    def __init__(self, host, port):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.bind(('', port))
        self.listen(1)

    def handle_accept(self):
        socket, address = self.accept()
        print 'Connection by', address
        EchoHandler(socket)

class EchoHandler(asyncore.dispatcher_with_send):
    def handle_read(self):
        self.out_buffer = self.recv(1024)
        if not self.out_buffer:
            self.close()

s = Server('', 5007)
asyncore.loop()

和这里的客户端:

import asyncore, socket

class Client(asyncore.dispatcher_with_send):
    def __init__(self, host, port, message):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connect((host, port))
        self.out_buffer = message

    def handle_close(self):
        self.close()

    def handle_read(self):
        print 'Received', self.recv(1024)
        self.close()

c = Client('', 5007, 'Hello, world')
asyncore.loop()

有一些模糊的情况下,这code不正确处理,但他们的解释是枯燥和复杂,和code已经作出这样的回答够长了。

There are a few obscure cases that this code doesn't handle correctly, but explaining them is boring and complicated, and the code has already made this answer long enough.

现在,这里的一些code,做基本同样的事情,与扭曲。首先,服务器

Now, here's some code that does basically the same thing, with Twisted. First, the server:

from twisted.internet import reactor, protocol as p

class Echo(p.Protocol):
    def dataReceived(self, data):
        self.transport.write(data)

class EchoFactory(p.Factory):
    def buildProtocol(self, addr):
        print 'Connection by', addr
        return Echo()

reactor.listenTCP(5007, EchoFactory())
reactor.run()

而现在,客户端:

And now, the client:

from twisted.internet import reactor, protocol as p

class EchoClient(p.Protocol):
    def connectionMade(self):
        self.transport.write(self.factory.data)

    def dataReceived(self, data):
        print 'Received:', data
        self.transport.loseConnection()

class EchoClientFactory(p.ClientFactory):
    protocol = EchoClient
    def __init__(self, data):
        self.data = data

reactor.connectTCP('localhost', 5007, EchoClientFactory('Hello, world'))
reactor.run()

有一对夫妇的事情,我想请你注意。首先,被扭曲的例子是缩短25%,甚至东西这个微不足道的。 40线asyncore,只有30扭曲。随着你的成长的协议更为复杂,这种差异会越来越大,因为你需要写越来越多的支持code表示,将已被扭曲为您提供了asyncore。

There are a couple of things that I'd like to draw your attention to. First of all, the Twisted example is 25% shorter, even for something this trivial. 40 lines for asyncore, only 30 for Twisted. As your protocol grows more complex, this difference will get bigger and bigger, as you need to write more and more support code for asyncore that would have been provided for you by Twisted.

二,Twisted提供了的完全抽象化的。随着asyncore例如,你必须使用插座模块做实际的组网; asyncore只提供复用。这是一个问题,如果你需要等平台上运行的Windows 便携行为。这也意味着,asyncore完全缺乏设施做其他平台上的异步子进程的通信;你不能随心所欲的东西文件描述符到Windows上的选择()电话。

Second, Twisted provides a complete abstraction. With the asyncore example, you have to use the socket module to do the actual networking; asyncore provides only multiplexing. This is a problem if you need portable behavior on platforms such as Windows. It also means that asyncore completely lacks facilities for doing asynchronous sub-process communication on other platforms; you can't stuff arbitrary file descriptors into a select() call on Windows.

三,扭曲的例子是的交通中性的。 回声 EchoFactory EchoClient 和<$ C的无$ C> EchoClientFactory 是在特定的TCP任何方式。您可以通过这些类为可以通过SSH或SSL或UNIX套接字或管道连接一个库,仅通过改变一个 connectTCP / listenTCP 底部电话。这一点很重要,因为直接在协议逻辑支持像TLS是非常棘手的。例如,在TLS中一个写将触发在较低水平读。所以,你需要将这些问题单独拿出来让他们的权利。

Third, the Twisted example is transport neutral. None of Echo and EchoFactory and EchoClient and EchoClientFactory is in any way specific to TCP. You can make these classes into a library that can be connected via SSH, or SSL, or a UNIX socket, or a pipe, only by changing the one connectTCP/listenTCP call at the bottom. This is important, as supporting something like TLS directly in your protocol logic is very tricky. For example, a 'write' in TLS will trigger a 'read' at the lower level. So, you need to separate these concerns out to get them right.

最后,具体到您的用例,如果你正在使用的MAC地址和以太网帧直接打交道,扭转包含的双绞线时,用于处理IP和以太网级网络的低级库。这不是扭曲的最积极地维护一部分;在code是很老。但是,它应该工作,如果没有,我们将采取任何的bug它当回事(最终)看到,他们得到修复。据我所知,有一个为asyncore没有可比性库,它肯定不包含任何此类code本身。

Finally, specific to your use-case, if you're dealing with MAC addresses and ethernet frames directly, Twisted contains Twisted Pair, a low-level library for dealing with IP and ethernet-level networking. This isn't the most actively maintained part of Twisted; the code is quite old. But, it should work, and if it doesn't we will take any bugs in it seriously and (eventually) see that they get fixed. As far as I'm aware, there's no comparable library for asyncore, and it certainly doesn't contain any such code itself.

这篇关于哪一种Python库异步会是最适合我的code? Asyncore?扭曲?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆