Skip to content

Instantly share code, notes, and snippets.

@jone
Created July 3, 2013 09:06
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 jone/5916528 to your computer and use it in GitHub Desktop.
Save jone/5916528 to your computer and use it in GitHub Desktop.
from memoize import memoize
import re
import shlex
import subprocess
def runcmd_get_exitcode(command, cwd=None):
return runcmd(command, cwd=cwd)[0]
def runcmd_get_stdout(command, cwd=None):
return runcmd(command, cwd=cwd)[1]
@memoize
def runcmd(command, cwd=None):
"""Advanced runcmd function with support for pipes and
subcommands.
E.g.:
'ps aux | grep iTerm'
'echo "foo" `ps aux | grep `echo iTerm` | cut -d \' \' -f 10` "bar"'
"""
if isinstance(command, unicode):
command = command.encode('utf-8')
subcommand = re.match('^(.*?)\`(.*)\`(.*?)$', command,
re.MULTILINE)
if subcommand:
subresult = runcmd(subcommand.groups()[1])
if subresult[0]:
return subresult
command = ''.join((
subcommand.groups()[0],
subresult[1],
subcommand.groups()[2]))
commands = command.split('|')
prev_proc = None
for cmd in commands:
if prev_proc:
input = prev_proc.stdout
else:
input = None
prev_proc = subprocess.Popen(shlex.split(cmd),
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
stdin=input,
cwd=cwd)
output, errors = prev_proc.communicate()
return prev_proc.poll(), output, errors
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment