杀死在线程内运行的子进程 [英] Killing sub process that run inside a thread
问题描述
我在 PyQT 5 中使用 python 3.5.3,并且我已经用它编写了 GUI.这个GUI用subprocess.run运行python代码python代码.
I'm using python 3.5.3 with PyQT 5 and I have written GUI with it. This GUI run python code python code with subprocess.run.
为了在子进程操作期间保持我的 GUI 处于活动状态而不被冻结,我在一个线程中运行子进程.
In order to leave my GUI active and not frozen during the subprocess operation , i'm running the subprocess in a thread.
在 GUI 中,我有停止按钮,如果用户按下 ,我想终止子进程.
In the GUI i have stop button that if the user pressed , I want to terminate the subprocess.
使用线程的终止方法杀死线程没有问题.但这并不会终止子进程.
I have no problem to kill the thread by using terminate method of the thread. But that's don't terminate the subprocess.
我尝试使用 Popen 而不是 run,但我无法让它像 subprocess.run 那样运行.另外,我更喜欢使用 Python 推荐的方式,这也给了我 check_error 选项
I've tried to use Popen instead of run but I cant make it to run as subprocess.run does. in addition , I prefer to use the recommended way by Python that's give me also the check_error option
这就是我使用子进程的方式:
This is how I use subprocess:
class c_run_test_thread(QtCore.QThread):
def __init__(self,test_file,log_file):
QtCore.QThread.__init__(self)
self.test_file = test_file
self.log_file = log_file
def __del__(self):
self.wait()
def run(self):
# Thread logic
try:
# Run the test with all prints and exceptions go to global log file
self.test_sub_process = subprocess.run(["python", self.test_file],stdout = self.log_file, stderr = self.log_file,check = True)
except subprocess.CalledProcessError as error:
print("Error : {}".format(error))
# Flush memory to file
self.log_file.flush(
def stop(self):
# Flush memory to file
self.log_file.flush()
然后我通过
# Stop test thread
self.thread_run_test.terminate()
总而言之,我想在杀死它的子进程的同时杀死线程.
To sum things up , I want to kill thread while killing its sub process too.
推荐答案
可能还有其他更简单的方法,但我所做的是
There may be other simpler ways to this, but what I did was to
- 使用
subprocess.Popen
运行子进程,而不是subprocess.run
,因为后者在进程终止前不会返回 - 使用
Popen.poll
检查进程是否终止 - 使用
Popen.kill
终止进程
- Use
subprocess.Popen
to run a sub process, instead ofsubprocess.run
, since the latter will not return before the process is terminated - Check if the process is terminated using
Popen.poll
- Kill the process using
Popen.kill
示例代码将是……像下面这样:
A sample code would be sth. like the following:
self.test_sub_process = subprocess.Popen(["python", self.test_file],
stdout=self.log_file,
stderr=self.log_file)
等待终止:
print("Return code: {}".format(self.test_sub_process.wait()))
或者如果您想在等待时做某事:
Or if you want to do something while waiting:
while self.test_sub_process.poll() is None:
doSomething()
print("Return code: {}".format(self.test_sub_process.poll()))
然后在thread_run_test.terminate()
中,可以杀掉进程
Then in thread_run_test.terminate()
, you can kill the process
self.test_sub_process.kill()
HTH.
这篇关于杀死在线程内运行的子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!