如何在python中的while循环中每次返回值

问题描述 投票:-1回答:3

我有以下代码

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

我想每次都能回归MSG怎么办?有人能帮我吗?

python-3.x can-bus canoe
3个回答
0
投票

您可能想要考虑使用yield关键字而不是return将函数转换为生成器。通过这种方式,使用yield MSG结束循环,您的函数将生成一系列消息,循环中每次迭代一次。

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

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

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

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

0
投票

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

0
投票

我不完全确定你想要什么,但我认为其中一个问题是每次都会创建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
© www.soinside.com 2019 - 2024. All rights reserved.