Last active
December 16, 2015 10:59
-
-
Save tylerthebuildor/5424313 to your computer and use it in GitHub Desktop.
Three different ways to run bash commands.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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