【问题标题】:Terminating program from a thread contained in try/except block从 try/except 块中包含的线程终止程序
【发布时间】:2022-06-12 09:06:38
【问题描述】:

谁能帮我从 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)

【问题讨论】:

  • 你为什么有一个空的except子句?
  • 这只是一个草图,所以这里没什么大不了的。这与我遇到的问题无关。我猜。

标签: python while-loop terminate


【解决方案1】:

sys.exit 尝试通过抛出 SystemExit 异常退出,该异常被 except 子句捕获。我不知道你为什么需要try/except,但你至少应该把它改成只捕获Exception,与BaseException不同,它只包括正常的异常,而不包括SystemExit这样的特殊异常.

【讨论】:

  • 我明白了,谢谢你的帮助。真的很受用。我需要这个 try/except 块,因为我的互联网连接非常糟糕,所以有时它会出现这些失误,无法连接 API。
猜你喜欢
  • 2022-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-13
  • 2014-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多