我正在开发 UBUNTU 并且我有文件 main.py
,里面有代码:
#!/usr/bin/env python3
# coding=utf-8
import os
import time
from subprocess import Popen, PIPE, call, signal
base_path = os.path.abspath('')
path_to_file = base_path + '/test_subprocess.py'
p = Popen(['gnome-terminal', "--", path_to_file])
time.sleep(2)
os.kill(p.pid, signal.SIGKILL)
我有 test_subprocess.py
这样的代码:
#!/usr/bin/env python3
# coding=utf-8
import time
def print_message():
while True:
print('I am working!')
time.sleep(0.5)
print_message()
我试图杀死子进程,但之后
os.kill(p.pid, signal.SIGKILL)
子进程仍在工作并打印 'I am working!'
如何完成子进程以及如何关闭 gnome 终端? 如果我选择了完全错误的方式。你能告诉我工作示例吗?
新版test_subprocess.py
#!/usr/bin/env python3
# coding=utf-8
import sys
from subprocess import signal
import time
def print_message():
while True:
print('I am working!')
time.sleep(0.5)
if signal.SIGKILL: # it is braking a loop when parent process terminate!
print('I am killing self!')
break
print_message()
我应该像上面那样做吗?
答案 0 :(得分:1)
您可以尝试以下操作:
p = Popen(['gnome-terminal', "--", path_to_file])
PIDs = p.pid
os.system("kill {0}".format(PIDs))
<块引用>
Popen.pid 子进程的进程ID。
注意,如果你将shell参数设置为True,就是这个过程 生成的外壳的 ID。
http://docs.python.org/library/subprocess.html
这至少会杀死正确的进程。不确定它是否会关闭终端。
编辑:终止进程并关闭终端:
p = Popen(['gnome-terminal', '--disable-factory', '-e', path_to_file], preexec_fn=os.setpgrp)
os.killpg(p.pid, signal.SIGINT)
归功于 https://stackoverflow.com/a/34690644/15793575,我为您的命令进行了修改:
--disable-factory
用于避免重复使用活动终端,以便我们可以通过子进程句柄杀死新创建的终端os.setpgrp
将 gnome-terminal 放在自己的进程组中,以便
os.killpg()
可用于向该组发送信号答案 1 :(得分:0)
Popen.pid
子进程的进程ID。
注意,如果你把shell参数设置为True,就是这个过程 生成的外壳的 ID。
尝试将 shell
构造函数的 Popen
参数设置为 False
。 (p = Popen(['gnome-terminal', "--", path_to_file])
-> p = Popen(['gnome-terminal', "--", path_to_file], shell=False)
)。不久前我遇到了类似的问题 - 这为我解决了。