Skip to content

Instantly share code, notes, and snippets.

@adamv
Created September 15, 2010 22:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save adamv/581582 to your computer and use it in GitHub Desktop.
Save adamv/581582 to your computer and use it in GitHub Desktop.
Common scripty helpers in Python
import sys
import os
import contextlib
from subprocess import Popen, PIPE
def die(message, error_code=1):
print message
sys.exit(error_code)
def system(command, print_command=False):
"Run a command, returning the exit code and output."
if print_command: print command
p = Popen(command)
return p.returncode
def run(command, print_command=False):
"Run a command, returning the exit code and output."
if print_command: print command
p = Popen(command, stdout=PIPE)
output, errput = p.communicate()
return p.returncode, output
def run2(command, print_command=False):
"Run a command, returning the exit code, output, and stderr."
p = Popen(command, stdout=PIPE, stderr=PIPE)
if print_command: print command
output, errput = p.communicate()
return p.returncode, output, errput
@contextlib.contextmanager
def working_folder(path):
"""Change the local current directory within a with block."""
last_folder = os.getcwd()
os.chdir(path)
yield path
os.chdir(last_folder)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment