问题描述
我对 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)
来测试此理论