I am trying to create a function to run a command
with timeout
, but at the same time, get standard output (stdout
) to display. I saw some answers, but not exactly what I am looking for.
- How to run a process with timeout and still get stdout at runtime (this is similar, but I need to return a
Popen
object. - How to get stdout from subprocess.Popen elegantly with timeout check? (also similar)
Function signature goes:
def run_with_timeout(command, timeout)
So far I am able to get stdout
to print at runtime, but I am not sure what's an robust way to timeout the application. Is there a robust way to do the timeout, or is there a better approach to this? I tried process.wait(timeout=timeout)
and process.communicate(timeout=timeout)
, but doesn't seem to work. I am trying to avoid using threads as well...
def run_with_timeout(command, timeout):
process = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True,
text=True,
)
output = ''
try:
for line in iter(process.stdout.readline, ''):
output += line
print(line)
process.stdout.close()
process.out = output
except subprocess.TimeoutExpired as te:
process.kill()
return process