Last active
June 4, 2019 08:23
-
-
Save andr1an/83ad1484f943d691a690dab32eaebf85 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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