Search code examples
pythonsubprocesssignalspopensigint

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. If the command hangs, I want the Ctrl-C to be passed to the subprocess. 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. This works but is there no way to send signals with subprocess.run()?

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

Solution

  • I don't think this can be done with run() but Popen does the trick. 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.

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