微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python没有以无限循环运行函数

如何解决Python没有以无限循环运行函数

我对 python 还是很陌生。最近,在玩 simpy 模块时,我遇到了 python 解释器的一些奇怪行为。我实现了 .flood() 函数,它应该是模拟的一部分。令我惊讶的是,它里面的调试没有显示在控制台上。这个函数内部有两个主要的代码块,所以我决定删除其中的一个(包含 while True: 循环)。

print("Starting program")
env = simpy.Environment()

#From Now on we assume the nodes to be 0-indexed 
#Create two routers we will connect manually
routers = [Router(env,i,debug = True) for i in range(3)]

# Create wire connection between routers

for i in range(2):
    addConnection(env,routers[i],routers[i + 1])

for router in routers:
    print("Line above .flood() call")
    router.flood()

env.run(until = 100)
    def flood(self):
        print(f"beginning to flood at {self.env.Now}")
        for wire in self.out_wire:
            wire.put(Packet(self.env.Now,random.randint(1,10**9),{"node": self.id,"neigh":self.neighbors}))

        while True:
            processes = [nei.get() for nei in self.in_wire]
            res = yield simpy.events.AnyOf(self.env,processes)
            print("RESULT: ",res,f"current time is {self.env.Now}")
            for packet in res:
                print(packet)

运行此代码会产生:

Starting program
Line above .flood() call
Line above .flood() call
Line above .flood() call

当我注释while True:部分时,输出如下:

Starting program
Line above .flood() call
beginning to flood at 0
Line above .flood() call
beginning to flood at 0
Line above .flood() call
beginning to flood at 0

现在我想知道我做错了什么?我知道,我的模拟仍然无法正常工作,而且可能我在那里做了一些不太聪明的事情,但除此之外还有没有人看到过类似的东西?

解决方法

所以我想如果 self.in_wire 是空的

processes = [nei.get() for nei in self.in_wire]

那么进程将是空的,因此将没有事件要产生,也没有资源要打印。 No yield 意味着您的无限循环不会停止/暂停阻塞您的代码。

您可以通过在循环底部添加 yield env.timeout(1) 来测试此理论

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。