Jul
18
2010
18
2010
Some examples using the subprocess python module.
Make a simple system call:
#! /usr/bin/env python import subprocess # Use a sequence of args return_code = subprocess.call(["echo", "hello world"]) # Set shell=true so we can use a simple string for the command return_code = subprocess.call("echo hello world", shell=True) # subprocess.call() is equivalent to using subprocess.Popen() and wait() proc = subprocess.Popen("echo hello world", shell=True) return_code = proc.wait() # wait for process to finish so we can get the return code
Control stderr and stdout:
#! /usr/bin/env python import subprocess # Put stderr and stdout into pipes proc = subprocess.Popen("echo hello stdout; echo hello stderr >&2", \ shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE) return_code = proc.wait() # Read from pipes for line in proc.stdout: print("stdout: " + line.rstrip()) for line in proc.stderr: print("stderr: " + line.rstrip())