Reputation:
I am using subprocess.run
to run a command and capture the output like so:
proc = subprocess.run([commandAndFlags], capture_output=True)
if proc.stdout:
print('stdout:', str(proc.stdout))
if proc.stderr:
print('stderr:', str(proc.stderr))
I would like to add a timeout, but still capture any output sent to stdout/stderr before the timeout goes off.
However, if I simple add the timeout and wrap it in a try/except, I cannot capture the subprocess output.
try:
proc = subprocess.run([commandAndFlags], capture_output=True, timeout=2000)
except subprocess.TimeoutExpired:
print('Timeout!!')
if proc.stdout:
print('stdout:', str(proc.stdout))
if proc.stderr:
print('stderr:', str(proc.stderr))
Now proc
is not defined when I try to print stdout/stderr.
How can I set a timeout but still capture any output that was printed before the timeout?
Upvotes: 3
Views: 1789
Reputation: 1321
You can still use the capture_output
attribute from your original code, and when the TimeoutExpired
exception is thrown, you can collect stdout
and stderr
from there. For example:
try:
proc = subprocess.run([commandAndFlags], capture_output=True, text=True, timeout=2000)
outs = proc.stdout
errs = proc.stderr
except subprocess.TimeoutExpired as timeErr:
outs = timeErr.stdout
errs = timeErr.stderr
Upvotes: 5
Reputation:
Eventually I figured out that you can pass files directly to subprocess.run
.
outfile = 'outfile.txt'
errfile = 'errfile.txt'
try:
proc = subprocess.run([commandAndFlags], timeout=2000
stdout=open(outfile, 'w'), stderr=open(errfile, 'w'))
except subprocess.TimeoutExpired:
print('Timeout!!')
# check if outfile/errfile files exist and print contents
subprocess will save stdout/stderr directly to a file that can be viewed later, regardless of if the subprocess was stopped by a timeout.
Upvotes: 0