Created
February 9, 2014 03:41
-
-
Save andrewgho/8893932 to your computer and use it in GitHub Desktop.
Demonstrate Python subprocess polling and termination
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# demo_subprocess.py - demonstrate Python subprocess polling and termination | |
# Andrew Ho (andrew@zeuscat.com) | |
import os, time, subprocess | |
sleep_for = 5 # How long in seconds should our test subprocess sleeps | |
timeout_after = 3 # Send SIGTERM to the subprocess after this many seconds | |
poll_delay = 0.5 # Sleep this long between polling for subprocess status | |
# Record begin time and fork a subprocess that sleeps for sleep_for seconds | |
begin = time.time() | |
child = subprocess.Popen(["sleep", str(sleep_for)]) | |
print "Parent pid = " + str(os.getpid()) | |
print "Forked child pid = " + str(child.pid) | |
# Poll for whether the subprocess has terminated | |
while(child.poll()) is None: | |
elapsed = time.time() - begin | |
print "Elapsed time = {0:.3f}s".format(elapsed) | |
if timeout_after > 0 and elapsed > timeout_after: | |
print "Terminating child" | |
child.terminate() | |
child.wait() | |
break | |
time.sleep(poll_delay) | |
elapsed = time.time() - begin | |
print "Total elapsed time = {0:.3f}s".format(elapsed) | |
print "Return value = " + str(child.returncode) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Change timeout_after to 0 to turn off premature termination, set the sleep_for longer to inspect the process table from another terminal session.