Skip to content

Instantly share code, notes, and snippets.

@tylerbuchea
Last active December 16, 2015 10:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tylerbuchea/5424313 to your computer and use it in GitHub Desktop.
Save tylerbuchea/5424313 to your computer and use it in GitHub Desktop.
Three different ways to run bash commands.
import subprocess
#! /usr/bin/env python
import subprocess
# Use a sequence of args
return_code = subprocess.call(["echo", "hello sequence"])
# Set shell=true so we can use a simple string for the command
return_code = subprocess.call("echo hello string", shell=True)
# subprocess.call() is equivalent to using subprocess.Popen() and wait()
proc = subprocess.Popen("echo hello popen", shell=True)
return_code = proc.wait() # wait for process to finish so we can get the return code
#! /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())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment