本文介绍了终止使用子进程打开的 gnome 终端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用子进程和命令 'gnome-terminal -e bash
' 我可以根据需要打开一个 gnome 终端(并让它一直存在).这可以通过
Using subprocess and the command 'gnome-terminal -e bash
' I can open up a gnome-terminal as desired (and have it stick around). This is done with either
p=subprocess.Popen(['gnome-terminal', '-e', 'bash'])
或
p=subprocess.Popen(['gnome-terminal -e bash'], shell=True)
但我无法使用 p.terminate()
或 p.kill()
关闭终端.据我了解,这在使用 shell=True
时有点棘手,但我没想到会遇到问题.
but I cannot close the terminal using p.terminate()
or p.kill()
. From what I understand, this is a little trickier when using shell=True
but I did not expect to run into problems otherwise.
推荐答案
要终止终端及其子进程(在同一进程组中):
To terminate a terminal and its children (in the same process group):
#!/usr/bin/env python
import os
import signal
import subprocess
p = subprocess.Popen(['gnome-terminal', '--disable-factory', '-e', 'bash'],
preexec_fn=os.setpgrp)
# do something here...
os.killpg(p.pid, signal.SIGINT)
--disable-factory
用于避免重复使用活动终端,以便我们可以通过subprocess
句柄杀死新创建的终端os.setpgrp
将gnome-terminal
放在它自己的进程组中,以便os.killpg()
可用于将信号发送到本组--disable-factory
is used to avoid re-using an active terminal so that we can kill newly created terminal via thesubprocess
handleos.setpgrp
putsgnome-terminal
in its own process group so thatos.killpg()
could be used to send signal to this group
这篇关于终止使用子进程打开的 gnome 终端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!