Use named tuple for return value

This commit is contained in:
facetoe 2015-05-20 21:51:26 +08:00
parent a610722b6d
commit 5448e38d14

View File

@ -1,6 +1,9 @@
# from subprocess import CalledProcessError # from subprocess import CalledProcessError
from collections import namedtuple
import subprocess import subprocess
CommandResult = namedtuple("Result", ['rc', 'out', 'err'])
def run_through_shell(command, enable_shell=False): def run_through_shell(command, enable_shell=False):
""" """
@ -10,10 +13,11 @@ def run_through_shell(command, enable_shell=False):
Don't use this function with programs that outputs lots of data since the output is saved Don't use this function with programs that outputs lots of data since the output is saved
in one variable in one variable
""" """
returncode = None returncode = None
stderr = None
try: try:
proc = subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=enable_shell) proc = subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=enable_shell)
out, stderr = proc.communicate() out, stderr = proc.communicate()
out = out.decode("UTF-8") out = out.decode("UTF-8")
stderr = stderr.decode("UTF-8") stderr = stderr.decode("UTF-8")
@ -26,4 +30,4 @@ def run_through_shell(command, enable_shell=False):
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as e:
out = e.output out = e.output
return returncode, out, stderr return CommandResult(returncode, out, stderr)