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

标签 python multithreading testing scripting

大家好,我是 Python 和多线程编程的新手。我有一个脚本通过一些测试步骤运行。同时这正在运行我想创建一个线程,该线程以一定间隔轮询并读取是否有任何进程在执行期间崩溃。我有一个获取此信息的功能。我的问题是,每当我得到一个进程崩溃时,我如何从该线程抛出异常。我当前的线程看起来像这样:

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)

然而,问题是异常仅在该线程中引发,而不是在主线程中引发。我想在那里抛出相同的异常并退出脚本。我对这个线程所做的是在开始所有测试步骤之前创建一个对象并将其设置为守护线程。当我的测试步骤完成后,我想在关闭模拟之前终止这个线程。所有这一切都是通过以下方式完成的:

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()

我不认为队列在我的场景中是可能的,因为我仍然需要在主线程中执行我的测试步骤。

感谢任何帮助!

最佳答案

您可以使用回溯模块将异常保存为变量。在您正在运行的线程中并期望出现异常,请尝试:

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()

在主线程中访问变量:

print(self.exception_var)

或者你想在这里做什么。请记住,在没有看到您的进程如何崩溃的情况下,我不确定这正是您想要的。这确实需要崩溃的进程实际导致异常,因此使用回溯。如果他们不这样做,那么您可能必须手动引发异常。这里有一个很好的答案: Manually raising (throwing) an exception in Python

关于python - 在 Python 的主线程中捕获线程的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42506949/

相关文章:

getProgress() 和 getNewValue() 之间的 Java 区别

testing - 如何定义仅限于包的测试任务?

angular - 确保在测试中填充了 ngrx 存储

Python - 如何从字符串中提取地址或如何在不同行的内容之前获取单词?

python - 从类方法创建新的类实例

python - 从 Python 调用 C/C++ 代码

C# 无法关闭后台 worker 创建的表单

c++ - qt中的条件变量,在哪里声明

c# - 如何从wcf获取业务异常?

python - 在tkinter中,为什么我必须单独使用 'grid'函数?