Skip to content

Instantly share code, notes, and snippets.

@tsarenkotxt
Last active April 18, 2022 14:02
Show Gist options
  • Save tsarenkotxt/604e7cac6d80be8b30987199b155e28e to your computer and use it in GitHub Desktop.
Save tsarenkotxt/604e7cac6d80be8b30987199b155e28e to your computer and use it in GitHub Desktop.
Python execute shell commands (unix)

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment