Skip to content

Instantly share code, notes, and snippets.

@gregglind
Created November 10, 2010 19:20
Show Gist options
  • Save gregglind/671352 to your computer and use it in GitHub Desktop.
Save gregglind/671352 to your computer and use it in GitHub Desktop.
Subprocess callout for python
import shlex
from subprocess import Popen, PIPE
def is_stringy(x):
'''
Is x a multiple type (like list, dict, tuple), or a 'single' type,
such as string.
>>> is_stringy(xrange(3))
False
>>> is_stringy(u'blah')
True
'''
return not hasattr(x,"__iter__")
def shell(args_or_command, input='',**kwargs):
''' uses subprocess pipes to call out to the shell.
Args:
args_or_command: args to the command, or command string
input: what should go to stdin of the process
kwargs: goes to Popen, see help(subprocess.Popen) for a list.
Returns:
stdout, stderr
>>> shell('basename /a/hello')
('hello\n','')
'''
if is_stringy(args_or_command):
args = shlex.split(args_or_command)
else:
args = args_or_command
stdout = kwargs.pop('stdout',PIPE)
stderr = kwargs.pop('stderr',PIPE)
p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE,**kwargs)
stdout, stderr = p.communicate(input=input)
return stdout, stderr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment