我有一个 Connection 类型,用于包装来自 asyncio 的读/写流对。
class Connection(object):
def __init__(self, stream_in, stream_out):
self._streams_ = (stream_in, stream_out)
def read(self, n_bytes: int = -1):
stream = self._streams_[0]
return stream.read(n_bytes)
def write(self, bytes_: bytes):
stream = self._streams_[1]
stream.write(bytes_)
yield from stream.drain()
当一个新的客户端连接到服务器时,new_connection 将创建一个新的Connection 对象,并期望接收 4 个字节。
@asyncio.coroutine
def new_connection(stream_in, stream_out):
conn = Connection(stream_in, stream_out)
data = yield from conn.read(4)
print(data)
客户端发送 4 个字节。
@asyncio.coroutine
def client(loop):
...
conn = Connection(stream_in, stream_out)
yield from conn.write(b'test')
这按我的预期工作,但我必须为每次调用 read 和 write 编写 yield from。为此,我尝试将 yield from 移动到 Connection。
def read(self, n_bytes: int = -1):
stream = self._streams_[0]
data = yield from stream.read(n_bytes)
return data
但是,我得到了一个生成器对象,而不是预期的数据字节。
<generator object StreamReader.read at 0x1109983b8>
所以,对于每次调用 read 和 write,我必须小心让 yield from。我的目标是将 new_connection 减少到以下内容。
@asyncio.coroutine
def new_connection(stream_in, stream_out):
conn = Connection(stream_in, stream_out)
print(conn.read(4))
最佳答案
因为 StreamReader.read is a coroutine ,调用它的唯一选择是 a) 将它包装在 Task 中或 Future 并通过事件循环运行它,b) await从使用 async def 定义的协程中获取它, 或 c) 使用 yield from它来自一个协程,该协程定义为用 @asyncio.coroutine 装饰的函数.
自从 Connection.read从事件循环调用(通过协程 new_connection ),您不能重用该事件循环来运行 Task或 Future对于 StreamReader.read : event loops can't be started while they're already running .您要么必须 stop the event loop (灾难性的,可能无法正确执行)或 create a new event loop (凌乱并违背了使用协程的目的)。这些都不是可取的,所以Connection.read需要是协程或 async功能。
其他两个选项(await 协程中的 async def 或 yield from 修饰函数中的 @asyncio.coroutine)大部分是等效的。唯一的区别是 async def and await were added in Python 3.5 ,所以对于 3.4,使用 yield from和 @asyncio.coroutine是唯一的选择(协程和 asyncio 在 3.4 之前不存在,因此其他版本无关紧要)。就个人而言,我更喜欢使用 async def和 await , 因为用 async def 定义协程比装饰器更干净,更清晰。
简而言之:有Connection.read和 new_connection是协程(使用装饰器或 async 关键字),并使用 await (或 yield from )调用其他协程( await conn.read(4) 中的 new_connection 和 await self.__in.read(n_bytes) 中的 Connection.read )。
关于python - 从流中产生的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45899959/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
我正在尝试设置一个puppet节点,但rubygems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由rubygems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co
我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco
我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返