我有一個running變數負責程式是否正在運行。還有一個回圈,只要running == True. 這個回圈包含許多函式,每個函式都需要 1 秒才能完成。
因此,如果在回圈的迭代程序中將 的值running更改為False直到迭代完全完成,則將執行操作。
對我來說,一旦值running變為False,回圈立即中斷(嗯,或幾乎立即),這是必要的。
我有這個解決方案:
running = True
while running:
do_something1(time_length=1)
if not running:
break
do_something2(time_length=1)
if not running:
break
do_something3(time_length=1)
if not running:
break
do_something4(time_length=1)
if not running:
break
do_something5(time_length=1)
if not running:
break
do_something6(time_length=1)
if not running:
break
# etc.
但是,這個選項看起來很笨拙并且占用了大量空間。是否可以不在每個動作之前規定一個條件,而只在開始時規定它?
UPD 1: 由于我沒有完全展示代碼,據我了解,答案不太適合我。
所有變數和函式都在類中。代碼本身看起來像這樣。
from threading import Thread
class SomeClass:
def __init__(self):
self.running = True
def toggle_running_flag(self):
# this function toggles self.running by user input
self.running = not self.running
if self.running:
Thread(target=self.do_all_of_this).start()
def do_something1(self):
# do something
pass
def do_something2(self):
# do something
pass
def do_something3(self):
# do something
pass
def do_all_of_this(self):
while self.running:
self.do_something1()
if not self.running:
break
self.do_something2()
if not self.running:
break
self.do_something3()
uj5u.com熱心網友回復:
您可以使用例外來代替該標志變數。請注意,例外不僅僅針對“壞東西”,例如,StopIteration例外是迭代器如何發出信號表明它們已完成。
演示:
from contextlib import suppress
class StopRunning(Exception):
pass
def do_something1():
print('do_something1')
raise StopRunning
def do_something2():
print('do_something2')
with suppress(StopRunning):
while True:
do_something1()
do_something2()
print('done')
輸出:
do_something1
done
在線嘗試!
uj5u.com熱心網友回復:
這是您可以做到的一種方式。您可以創建一個在您必須執行的函式之間無限回圈的函式:
from itertools import cycle
class SomeClass:
def __init__(self):
self.running = True
def toggle_running_flag(self):
# this function toggles self.running by user input
self.running = True
Thread(target=self.do_all_of_this).start()
def do_all_of_this(self):
self.work = [self.do_something1, self.do_something2, self.do_something3]
for func in cycle(self.work):
func()
if not self.running:
return
每次迭代后檢查您的程式是否仍應運行。如果不回傳(停止迭代)
uj5u.com熱心網友回復:
是各種do_somethings設定running = False嗎?依賴全域變數不是一個很好的模式。
更新全域標志的一種替代方法是do_somethingN拋出例外以停止執行:
from do_things import StopRunning, do_something1, do_something2, # etc
try:
while True:
do_something1(time_length=1)
do_something2(time_length=1)
do_something3(time_length=1)
do_something4(time_length=1)
do_something5(time_length=1)
do_something6(time_length=1)
except StopRunning:
pass
別處:
# do_things.py
class StopRunning(Exception):
pass
def do_something1(time_length):
if time_length > 42:
raise StopRunning
# etc
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/427466.html
標籤:Python python-3.x
上一篇:如何在cmd/python中使用Ctrl C禁用中斷
下一篇:將最后一列加1的For回圈模式
