【问题标题】:How return the value every time in while loop in python如何在python的while循环中每次返回值
【发布时间】:2019-09-16 15:23:30
【问题描述】:

我有以下代码

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()

我想每次都退回味精怎么办? 有人可以帮我吗?

【问题讨论】:

  • 你能试着描述你想要的行为吗?我假设bus.recv() 方法返回当前可用的数据(一个或多个字节)。您想要结果一出来,还是在公共汽车上经过一定程度的沉默后?你想要所有数据(连接)还是只想要最后一个字节?我认为您的代码存在多个问题,但我需要更多信息才能提供一个好的答案。

标签: python-3.x can-bus canoe


【解决方案1】:

您可能想要考虑将您的函数变成一个生成器,使用 yield 关键字而不是 return。这样,以yield MSG 结束您的循环,您的函数将生成一系列消息,循环中的每次迭代都有一条消息。

当您的生成器结束时,即MSGNone,将引发StopIteration 异常,使for 循环按预期终止。

最后,您可以按如下方式构建代码:

def callee():
    while ...:
        elem = ...
        yield elem

def caller():
    for elem in callee():
        ...

【讨论】:

  • 它只来了一次,出来它没有用
  • 您能否提供一个示例来解释您对此解决方案的问题?
  • ~~~~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 def abcd_2(): for MSG in abcd(): print(MSG) return MSG if name == 'main': abcd_2() ~~~~~~ 我试过了,但是没有输出
  • 您的代码在评论中不可读,您能否更新您的原始帖子,在底部添加新版本的代码?
【解决方案2】:

正如@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.

【讨论】:

  • 代替打印操作我想返回
  • 您可以将所有产量收集到一个列表中并进行处理。
【解决方案3】:

我不完全确定您想要什么,但我认为问题之一是每次都会创建 bus 对象。你可以试试下面的代码。我无法自己测试它,因为我没有可用的 CAN 总线。我也不确定该方法应该返回什么。如果你能改进问题,我也可以改进答案:-)

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

【讨论】:

    猜你喜欢
    • 2012-10-26
    • 2015-02-24
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    • 1970-01-01
    • 2016-05-29
    • 2013-02-06
    • 2016-05-21
    相关资源
    最近更新 更多