[英]Terminating program from a thread contained in try/except block
有人可以幫我從 if 語句中終止這個程序。 我無法完成它。 我已經嘗試使用 sys.quit 進行此操作,但它似乎不適合 try/except 塊,並且我無法跳出線程內的循環。 我可以在 run() 方法中做到這一點,但是構建一個線程然后嘗試在它之外做一些事情有點沒用。 感覺好像有什么不對勁。 這是代碼:
class TradingBot:
def init(self) -> None:
self.api = tradeapi.REST(key_id=API_KEY, secret_key=SECRET_KEY, base_url=BASE_URL, api_version='v2')
def simple_thread(self):
try:
account = self.api.get_account()
clock = self.api.get_clock()
balance_change = float(account.equity) - float(account.last_equity)
condition_1 = balance_change > 0
condition_2 = balance_change < 0
if condition_1:
pass
#Figure out something to quit if condition 1 is met
elif condition_2:
pass
#Figure out something to quit if condition 2 is met
except:
print('Some error has occured')
def run(self):
while True:
execute = threading.Thread(target=self.simple_thread())
execute.start()
time.sleep(1)
sys.exit
嘗試通過拋出SystemExit
異常退出,該異常被裸except
子句捕獲。 我不確定你為什么需要try
/ except
,但你可能至少應該將它更改為僅捕獲Exception
,與BaseException
不同,它只包括正常異常,而不包括諸如SystemExit
之類的特殊異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.