The Python Subprocess module is a highly flexible way of running background processes in Python. Here are two functions that show how to run external shell commands, one will wait for the command to return and the other runs in the background allowing the controlling script to stop it as required.
Passing unsanitized input to these functions will not end well.
1 2 3 4 5 6 7 8 9 10 11 |
import subprocess def background_run_command(cmd): """Runs a bash command in the background, returns the Popen instance, does not block.""" return subprocess.Popen( [ cmd ], shell=True, executable='/bin/bash') def run_command(cmd): """ Runs an external command in bash, waits until the process has returned and returns output/ return code.""" proc = subprocess.Popen( [ cmd ], shell=True, executable='/bin/bash', stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) proc.wait() return (proc.returncode, proc.stdout) |
Questions? Comments?