繁体   English   中英

从 try/except 块中包含的线程终止程序

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM