Skip to content

Instantly share code, notes, and snippets.

@SpotlightKid
Last active December 12, 2017 00:44
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 SpotlightKid/78a951b153bab8d69f808af33581b5fb to your computer and use it in GitHub Desktop.
Save SpotlightKid/78a951b153bab8d69f808af33581b5fb to your computer and use it in GitHub Desktop.
Handy utility function to get output of shell command piping input to stdin (requires Python 3.5+).
>>> pipe('md5sum', 'This is a test')
--> 'ce114e4501d2f4e2dcea3e17b546f339 -\n'
>>> pipe('md5sum', b'This is a test')
--> b'ce114e4501d2f4e2dcea3e17b546f339 -\n'
>>> pipe(['gzip', '-c'], b'This is a test')
b'\x1f\x8b\x08\x00\xd6\x91\x13Z\x00\x03\x0b\xc9\xc8,V\x00\xa2D\x85\x92\xd4\xe2\x12\x002\x9fz\xc0\x0e\x00\x00\x00'
>>> pipe('bash', 'ls').splitlines()
--> ['pipe.py', 'test.txt']
>>> pipe('bash', 'ls foo', env={'LANG': 'en'})
ls: cannot access 'foo': No such file or directory
--> ''
>>> pipe('bash', 'ls foo', stderr='drop')
--> ''
>>> pipe('bash', 'ls foo', stderr='capture', env={'LANG': 'en'})
--> ('', "ls: cannot access 'foo': No such file or directory\n")
>>> pipe('bash', 'ls foo', stderr='redirect', env={'LANG': 'en'})
--> "ls: cannot access 'foo': No such file or directory\n"
"""Get output of shell command piping input to stdin."""
from subprocess import DEVNULL, PIPE, run, STDOUT
def pipe(cmd, input='', stderr=None, **kwargs):
kwargs['stdout'] = PIPE
kwargs['stderr'] = {'redirect': STDOUT, 'capture': PIPE, 'drop': DEVNULL}.get(stderr, stderr)
kwargs.setdefault('encoding', 'utf-8' if isinstance(input, str) else None)
res = run(cmd, input=input, **kwargs)
return (res.stdout, res.stderr) if stderr == 'capture' else res.stdout
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment