python - 杀死进程不杀死子进程并且不关闭终端窗口

标签 python subprocess popen gnome-terminal

我在 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()
我应该像上面那样做吗?

最佳答案

您可以尝试以下操作:

p = Popen(['gnome-terminal', "--",  path_to_file])
PIDs = p.pid
os.system("kill {0}".format(PIDs))

Popen.pid The process ID of the child process.

Note that if you set the shell argument to True, this is the process ID of the spawned shell.


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()可用于向该组发送信号
  • 关于python - 杀死进程不杀死子进程并且不关闭终端窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67348716/

    相关文章:

    c - 在执行 _popen 时隐藏控制台窗口

    python - 如何在Python中为str子代覆盖ord行为?

    python - 我想从 Trustpilot 评论中抓取用户和位置信息

    python - 如何使用 Python 为不同的前缀同时运行 AWS S3 sync 命令

    python - 如何执行程序或调用系统命令?

    php - 使用 proc_open() 在 PHP 中运行 C 可执行文件

    python - 从 pandas 大数据集中获取犯罪 'count'

    python - ImportError ("Couldn' 找不到 FluidSynth 库。”)

    python - 带有短命令的间歇性 "OSError: [Errno 7] Argument list too long"(~125 个字符)

    c - popen/pclose 的替代品?