Python 3 通过发送 Ctrl C 停止子进程

标签 python python-3.x linux gpu

我有一些 GPU 测试软件,我正在尝试使用 python3 实现自动化,测试通常会运行 3 分钟,然后由用户使用 ctrl+c 取消生成以下输出

GPU test output

用 ctrl+c 退出后,测试可以再次运行没有问题

当尝试使用子进程 popen 自动执行此操作并发送 SIGINT 或 SIGTERM 时,我得到的结果与使用键盘输入时的结果不同。脚本突然退出,在随后的运行中找不到 gpus(假设它没有正确卸载驱动程序)

from subprocess import Popen, PIPE
from signal import SIGINT
from time import time


def check_subproc_alive(subproc):
    return subproc.poll() is None

def print_subproc(subproc, timer=True):
    start_time = time()
    while check_subproc_alive(subproc):
        line = subproc.stdout.readline().decode('utf-8')
        print(line, end="")
        if timer and (time() - start_time) > 10:
            break


subproc = Popen(['./gpu_test.sh', '-t', '1'], stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=False)

print_subproc(subproc)

subproc.send_signal(SIGINT)

print_subproc(subproc, False)

如何将 ctrl+c 发送到子进程,就像用户键入它一样?

**更新

import subprocess


def start(executable_file):
    return subprocess.Popen(
        executable_file,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )


def read(process):
    return process.stdout.readline().decode("utf-8").strip()


def write(process):
    process.stdin.write('\x03'.encode())
    process.stdin.flush()

def terminate(process):
    process.stdin.close()
    process.terminate()
    process.wait(timeout=0.2)


process = start("./test.sh")
write(process)
for x in range(100):
    print(read(process))
terminate(process)

尝试了上面的代码并且可以让字符注册到虚拟 sh 脚本但是发送\x03 命令只发送一个空字符并且不会结束脚本

最佳答案

我想你可以使用这样的东西:

import signal
try:
    p=subprocess...
except KeyboardInterrupt:
    p.send_signal(signal.SIGINT)

关于Python 3 通过发送 Ctrl C 停止子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57608058/

相关文章:

python - 无法导入 TA-Lib - Python

python - 如何在python pdfkit中将html转换为pdf时设置页面大小

Python添加两组并删除重复元素

python - 如何将字符串中的 "\t"拆分为两个单独的字符 "\"和 "t"? (如何拆分转义序列?)

linux - 丢失的 TCP 数据包在哪里?

linux - 加入两个文件的第一列

python迭代器和线程安全

python - 重新排序数据框的列索引

python - 是否可以从 test_step() 函数保存文件?

linux - 如何为物联网设备(基于 Linux)进行软件部署?