Python 3.x 在python中,如何在while循环中每次返回值
我有下面的代码Python 3.x 在python中,如何在while循环中每次返回值,python-3.x,can-bus,canoe,Python 3.x,Can Bus,Canoe,我有下面的代码 import can def abcd(): bus = can.interface.Bus(channel= '1', bustype='vector',app_name = 'python-can') MSG = bus.recv(0.5) while MSG is not None: MSG = bus.recv(1) return MSG if __name__ == '__main__': abcd()
import can
def abcd():
bus = can.interface.Bus(channel= '1', bustype='vector',app_name = 'python-can')
MSG = bus.recv(0.5)
while MSG is not None:
MSG = bus.recv(1)
return MSG
if __name__ == '__main__':
abcd()
而我每次都想回味精我该怎么办?
有人能帮助我吗? < P>你可能想考虑将函数转换成生成器,使用<代码>收益率>代码>关键字,而不是<代码>返回< /代码>。这样,以
yield MSG
结束您的周期,您的函数将生成一系列消息,在周期中每次迭代一条
当生成器结束时,因此MSG
为None
,将引发StopIteration
异常,使for
循环按预期终止
最后,您可以按如下方式构造代码:
def callee():
while ...:
elem = ...
yield elem
def caller():
for elem in callee():
...
正如@Elia Geretto提到的,您可能需要将其转换为生成器函数。请告诉我这些更改是否有帮助
import can
def abcd():
bus = can.interface.Bus(channel= '1', bustype='vector',app_name = 'python-can')
MSG = bus.recv(0.5)
while MSG is not None:
MSG = bus.recv(1)
yield MSG
if __name__ == '__main__':
for op in abcd():
print(op) # or you can use next() as well.
我不完全确定您想要什么,但我认为问题之一是每次都会创建
bus
对象。您可以尝试以下代码。我不能自己测试,因为我没有CAN总线。我也不确定该方法应该返回什么。如果你能改进这个问题,我也能改进答案:-)
它只出现一次,但没有出现。请提供一个示例来解释此解决方案的问题好吗?~~~~~导入can def abcd():bus=can.interface.bus(channel='1',bustype='vector',app_name='python can')MSG=bus.recv(0.5),而MSG不是None:MSG=bus.recv(1)生成MSG def abcd\u 2():对于abcd()中的消息:如果名称='main',则打印(消息)返回消息:abcd_2()~~~~~~~我试过了,但是没有任何输出。你的代码在评论中不可读,你能更新你的原始帖子吗?在底部添加新版本的代码吗?代替打印操作,我希望返回你可以收集所有的结果到一个列表中并进行处理。你能试着描述一下你想要的行为吗?我假设
bus.recv()
方法返回当前可用的数据(一个或多个字节)。您希望在数据可用时立即得到结果,还是在总线上经过一定程度的静默后得到结果?是否希望所有数据(串联)或者仅仅是最后一个字节?我认为您的代码存在多个问题,但是我需要更多的信息来提供一个好的答案。
import can
def read_from_can(bus):
msg = bus.recv(0.5)
while msg is not None:
msg = bus.recv(1)
return msg
def main():
# create bus interface only once
bus = can.interface.Bus(channel='1', bustype='vector', app_name='python-can')
# then read (for example) 10 times from bus
for i in range(10):
result = read_from_can(bus)
print(result)
if __name__ == '__main__':
main() # Tip: avoid putting your code here; use a method instead