A simple function to execute shell commands (unix):
import os, signal, subprocess
def execute(command, timeout=None):
process = subprocess.Popen(command,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, start_new_session=True, shell=True)
try:
output = process.communicate(timeout=timeout)
timeout_reached = False
except subprocess.TimeoutExpired:
os.killpg(os.getpgid(process.pid), signal.SIGKILL)
output = process.communicate()
timeout_reached = True
return process.returncode, timeout_reached, output[0].decode('utf-8')
Example:
return_code, timeout_reached, output = executor.execute('echo Hello World', 1)
print(f" return_code:\n{return_code}")
print(f" timeout_reached:\n{timeout_reached}")
print(f" output:\n{output}")
output:
return_code:
0
timeout_reached:
False
output:
Hello World