[英]Python did not run function with infinite loop
我對 python 還是很陌生。 最近,在玩 simpy 模塊時,我遇到了 python 解釋器的一些奇怪行為。 我實現了.flood() function,它應該是模擬的一部分。 令我驚訝的是,其中的調試沒有顯示在控制台上。 在這個 function 內部有兩個主要的代碼塊,所以我決定刪除其中一個(包含 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
當我評論時 True:部分,那么 output 如下:
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]
那么進程將是空的,因此不會有任何事件可以讓步,也沒有要打印的資源。 沒有產量意味着您的無限循環不會停止/暫停阻塞您的代碼。
您可以通過在循環底部添加一個yield env.timeout(1)
來測試這個理論
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.