如何让子进程处理ctrl-c?

问题描述 投票:0回答:1

我有一个Python文件parent.py作为包装器来启动另一个Python程序child.py。这是parent.py的主要部分:

p = subprocess.run(f"python -u {cmd} 2>&1 | tee -a {file_path}", shell=True)

我想用ctrl-c来控制子进程。所以在child.py中,我写了一个try- except来捕获KeyBoardInterrupt并处理它:

try:
    while True:
        pass
except KeyboardInterrupt:
    print("lalala~~~~~~~~~~~~~~~~~~~~~")

但是,如果我运行parent.py然后按ctrl-c,则parent已被终止,并且child.py无法处理中断(没有“lalala”输出):

^CTraceback(最近一次调用最后一次):文件 “/home/zxl/rcd_python1.py”,第 27 行,在 p = subprocess.run(f"python -u {cmd} 2>&1 | tee -a {file_path}", shell=True) 文件 “/home/zxl/programs/anaconda3/envs/pyg2/lib/python3.8/subprocess.py”, 第 495 行,正在运行 stdout, stderr = process.communicate(输入, timeout=timeout) 文件 “/home/zxl/programs/anaconda3/envs/pyg2/lib/python3.8/subprocess.py”, 第 1020 行,在通信中 self.wait() 文件“/home/zxl/programs/anaconda3/envs/pyg2/lib/python3.8/subprocess.py”, 第 1083 行,等待中 返回 self._wait(timeout=timeout) 文件“/home/zxl/programs/anaconda3/envs/pyg2/lib/python3.8/subprocess.py”, 第 1808 行,在 _wait 中 (pid, sts) = self._try_wait(0) 文件“/home/zxl/programs/anaconda3/envs/pyg2/lib/python3.8/subprocess.py”, 第 1766 行,在 _try_wait 中 (pid, sts) = os.waitpid(self.pid, wait_flags) 键盘中断

如何将 ctrl-c 发送到子进程并使其处理它,而不是终止一切?非常感谢~

python subprocess signals
1个回答
0
投票

我得到了你期望的输出。你的代码对我有用。

test_subprocess.py

import time

if __name__ == '__main__':
    while True:
        try:
            time.sleep(1)
        except KeyboardInterrupt:
            print("lalala")

test_subprocess_main.py

import subprocess

if __name__ == '__main__':
    print('Start')
    p = subprocess.run("python3 test_subprocess.py", shell=True, check=True)

输出。

Mac-sashi:有趣的 sashi$ python3 test_subprocess_main.py
开始
^克拉拉拉
回溯(最近一次调用最后一次):文件 “/Users/sashi/repos/fun/test_subprocess_main.py”,第 6 行,在 p = subprocess.run("python3 test_subprocess.py", shell=True, check=True) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^
文件 “/Users/sashi/.pyenv/versions/3.11.1/lib/python3.11/subprocess.py”, 550 号线,运行中 stdout, stderr = process.communicate(输入, 超时=超时) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 文件 “/Users/sashi/.pyenv/versions/3.11.1/lib/python3.11/subprocess.py”, 第 1199 行,在通信中 self.wait() 文件“/Users/sashi/.pyenv/versions/3.11.1/lib/python3.11/subprocess.py”, 第 1262 行,等待中 返回 self._wait(超时=超时) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 文件“/Users/sashi/.pyenv/versions/3.11.1/lib/python3.11/subprocess .py", 1997 行,在 _wait 中 (pid, sts) = self._try_wait(0) ^^^^^^^^^^^^^^^^^^ 文件“/Users/sashi/.pyenv/versions/3.11.1/lib/python3.11/subprocess.py”, 第 1955 行,在 _try_wait 中 (pid, sts) = os.waitpid(self.pid, wait_flags) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 键盘中断

你可以试试我发布的代码吗?对你有用吗?

© www.soinside.com 2019 - 2024. All rights reserved.