If the process doesn't terminate after timeout
seconds, a TimeoutExpired
exception is raised. Because the child process does not end if the timeout expires, to properly clean up you must explicitly end the child process and finish communication.
1def subprocess_timeout_noncompliant():
2 import subprocess
3 process = subprocess.Popen("ls -al",
4 bufsize=-1,
5 stdout=subprocess.PIPE,
6 stderr=subprocess.PIPE)
7 try:
8 # Noncompliant: fails to terminate the child process before
9 # the timeout expires.
10 outs, errs = process.communicate(timeout=15)
11 except subprocess.TimeoutExpired:
12 print("Timed out")
1def subprocess_timeout_compliant():
2 import subprocess
3 process = subprocess.Popen("ls -al",
4 bufsize=-1,
5 stdout=subprocess.PIPE,
6 stderr=subprocess.PIPE)
7 try:
8 # Compliant: makes sure to terminate the child process when
9 # the timeout expires.
10 outs, errs = process.communicate(timeout=15)
11 except subprocess.TimeoutExpired:
12 process.kill()
13 outs, errs = process.communicate()