终止使用子进程打开的 gnome 终端

Sha*_*erz 5 python terminal subprocess

使用 subprocess 和命令 ' gnome-terminal -e bash' 我可以根据需要打开一个 gnome 终端(并让它保留在周围)。这是通过以下任一方式完成的

p=subprocess.Popen(['gnome-terminal', '-e', 'bash'])
Run Code Online (Sandbox Code Playgroud)

或者

p=subprocess.Popen(['gnome-terminal -e bash'], shell=True)
Run Code Online (Sandbox Code Playgroud)

p.terminate()但我无法使用或关闭终端p.kill()。据我了解,这在使用时有点棘手shell=True,但我没想到会遇到问题。

jfs*_*jfs 5

终止终端及其子终端(在同一进程组中):

#!/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)
Run Code Online (Sandbox Code Playgroud)
  • --disable-factory用于避免重复使用活动终端,以便我们可以通过subprocess句柄杀死新创建的终端
  • os.setpgrp放入gnome-terminal自己的进程组,以便os.killpg()可以用来向该组发送信号

  • 只是更新:至少从版本 3.28.2 开始,不再支持 --disable-factory。我仍然对这个问题的答案感兴趣,因为这个解决方案对我不起作用! (2认同)