Skip to content

Instantly share code, notes, and snippets.

@andr1an
Last active June 4, 2019 08:23
Show Gist options
  • Save andr1an/83ad1484f943d691a690dab32eaebf85 to your computer and use it in GitHub Desktop.
Save andr1an/83ad1484f943d691a690dab32eaebf85 to your computer and use it in GitHub Desktop.
"""
Safe way to call subprocess.Popen.communicate() and str from it.
"""
def shell(exe, *args, **kwargs):
if sys.version_info >= (3, 6) and 'encoding' not in kwargs: # for Python >=3.6
kwargs['encoding'] = 'utf8'
args = [exe] + list(args)
proc = subprocess.Popen(args, stdout=subprocess.PIPE)
out, _ = proc.communicate()
if proc.returncode != 0:
raise RuntimeError('{} returned {}'.format(exe, proc.returncode))
if not isinstance(out, str): # for Python >3.0, <3.6
out = out.decode('utf-8')
return out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment