1

I am executing a bash script in Python using the tempfile and subprocess like so:

 with tempfile.NamedTemporaryFile() as scriptfile:
                scriptfile.write(teststr)
                scriptfile.flush()
                subprocess.call(['/bin/bash', scriptfile.name])

Here, teststr has the entire bash script within it. My question is, once it starts to execute, it doesn't capture keyboard interrupts like Ctrl+c and ctrl+z.

Is there anyway to interrupt the execution of the script once it has begun?

2
  • Show us your bash script. It probably traps SIGINT... Commented Aug 8, 2013 at 11:48
  • Can't reproduce. Even if child process executes signal(SIGINT, SIG_IGN) and enters infinite loop, signal is successfully delivered to Python parent (as it should be: entire process group is affected) where it raises an appropriate exception. EDIT: Oh, never mind: the child keeps running and that is the problem, probably. Commented Aug 8, 2013 at 11:52

1 Answer 1

1

I assume that the problem is that Python parent process receives SIGINT from Ctrl+C and quits with unhandled exception, but the child ignores signal and keeps running. That is the only scenario I was able to reproduce. Actual problem may differ. Catching exception and killing subprocess explicitly with SIGKILL may work.

Instead of subprocess.call:

proc = subprocess.Popen(['/bin/bash', scriptfile.name])
try:
    proc.wait()
except:
    proc.kill()
    raise
Sign up to request clarification or add additional context in comments.

1 Comment

Never use naked excepts: if you don't know what you're catching, then you don't know how to handle it. except KeyboardInterrupt is what you want here. And SIGKILL is a last resort, not a first one; SIGTERM is what you send when you want to give an arbirtrary process a chance at orderly clean-up.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.