Skip to content

Instantly share code, notes, and snippets.

@tomschr
Last active June 21, 2019 08:43
Show Gist options
  • Save tomschr/87cd5a9bb4c1e1d3af8ec32d32f0c702 to your computer and use it in GitHub Desktop.
Save tomschr/87cd5a9bb4c1e1d3af8ec32d32f0c702 to your computer and use it in GitHub Desktop.
Use subprocess.run for Python < 3.5
# Source: https://github.com/mitsuhiko/pipsi/blob/master/pipsi/__init__.py
from collections import namedtuple
import subprocess
def proc_output(s):
s = s.strip()
if not isinstance(s, str):
s = s.decode('utf-8', 'replace')
return s
try:
subprocess.run
def run(*args, **kw):
kw.update(stdout=subprocess.PIPE, stderr=subprocess.PIPE)
r = subprocess.run(*args, **kw)
r.stdout, r.stderr = map(proc_output, (r.stdout, r.stderr))
return r
except AttributeError: # no `subprocess.run`, py < 3.5
CompletedProcess = namedtuple('CompletedProcess',
('args', 'returncode', 'stdout', 'stderr'))
def run(argv, **kw):
p = subprocess.Popen(
argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kw)
out, err = map(proc_output, p.communicate())
return CompletedProcess(argv, p.returncode, out, err)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment