简体   繁体   English

Python:将 Ctrl-C 转发到子进程

[英]Python: Forwarding Ctrl-C to subprocess

I have a Slurm srun wrapper in Python 3.6 that validates command line arguments and then allows the real program to run with those arguments.我在 Python 3.6 中有一个 Slurm srun 包装器,它验证命令行参数,然后允许真正的程序使用这些参数运行。 If the command hangs, I want the Ctrl-C to be passed to the subprocess.如果命令挂起,我希望将 Ctrl-C 传递给子进程。 I don't care about the program's stdin/out/err;我不关心程序的标准输入/输出/错误; I want the user to interact with it as if there was no python wrapper.我希望用户与它进行交互,就好像没有 python 包装器一样。 This works but is there no way to send signals with subprocess.run()?这可行,但没有办法用 subprocess.run() 发送信号吗?

try:
    cmd = subprocess.Popen(['/usr/bin/srun'] + argv[1:])
    cmd.wait() 
except KeyboardInterrupt:
    cmd.send_signal(signal.SIGINT)

I don't think this can be done with run() but Popen does the trick.我不认为这可以用 run() 来完成,但 Popen 可以做到这一点。 With this change I can get all the output from srun (even after the Ctrl-C), as well as capture the exit value of srun.通过此更改,我可以从 srun 获取所有输出(即使在 Ctrl-C 之后),以及捕获 srun 的退出值。

try:
    with subprocess.Popen(['/usr/bin/srun'] + argv[1:]) as cmd:
        cmd.wait()
except KeyboardInterrupt:
    cmd.send_signal(SIGINT)
exit(cmd.returncode)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM