简体   繁体   English

在Python的主线程中捕获线程的异常

[英]Catch a thread's exception in the main thread in Python

Hi I'm new to Python and multithreaded programming. 嗨,我是Python和多线程编程的新手。 I have a script running through some test steps. 我有一个脚本运行一些测试步骤。 Meanwhile this is running I want to create a thread that polls with an interval and reads if any processes have crashed during execution. 同时这正在运行我想创建一个以间隔轮询的线程,并读取执行期间是否有任何进程崩溃。 I have a function which acquires this information. 我有一个获取此信息的功能。 My problem is how I can throw an exception from that thread whenever I get that a process has crashed. 我的问题是每当我得到一个进程崩溃时我怎么能从该线程抛出异常。 My current thread looks something like this: 我当前的线程看起来像这样:

class process_thread(threading.Thread):
  def __init__(self):
  threading.Thread.__init__(self)
  self.run_thread = True

  def run(self):
    while self.run_thread:
      if has_any_processes_crashed() == -1:
        self.run_thread = False
        raise MyStopException("A process has crashed") # This is the problematic line. It is only raised in this thread, not in main thread.
      else:
        time.sleep(3)

The problem is however that the exception is only raised in that thread and not in the main thread. 但问题是异常仅在该线程中引发而不在主线程中引发。 I want to throw the same exception there and exit the script. 我想在那里抛出相同的异常并退出脚本。 What I do with this thread is that I create an object before I start with all my test steps and set it as a Daemon thread. 我对这个线程做的是在开始我的所有测试步骤之前创建一个对象并将其设置为守护进程线程。 When my test steps are done I want to kill this thread before shutting down the simulation. 当我的测试步骤完成后,我想在关闭模拟之前杀死这个线程。 All this is done by: 所有这一切都是通过以

p_thread = process_thread()
p_thread.setDaemon(True)
p_thread.start()

# Executing all test steps here
# test_step_1
do_something_1()
# test_step_n
do_something_n()

p_thread.run_thread = False
p_thread.join()

I do not think that a Queue is possible in my scenario as I still need to execute my test steps in the main thread. 我不认为在我的场景中可以使用Queue,因为我仍然需要在主线程中执行我的测试步骤。

Any help is appreciated! 任何帮助表示赞赏!

You can save the exception as a variable using the traceback module. 您可以使用traceback模块将异常另存为变量。 In your thread that you are running and expect the exception, try: 在您运行的线程中并期望异常,请尝试:

import traceback

class process_thread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.run_thread = True

    def run(self):
        try:
            process that may crash()
        except:
            self.exception_var = traceback.format_exc()

The you access the variable in the main thread: 您在主线程中访问变量:

print(self.exception_var)

Or whatever you want to do with it here. 或者你想在这里做什么。 Bear in mind, without seeing how your processes crash, i'm not sure this is exactly what you want. 请记住,没有看到你的进程如何崩溃,我不确定这正是你想要的。 This does require that the processes that crash actually cause an exception, hence using traceback. 这确实需要崩溃的进程实际上导致异常,因此使用回溯。 If they don't, then you may have to manually raise an exception. 如果他们不这样做,那么您可能必须手动引发异常。 There is a great answer on doing that here: Manually raising (throwing) an exception in Python 这里有一个很好的答案: 在Python中手动引发(抛出)异常

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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