Search code examples
python-3.xsubprocesspopenwith-statement

How to return encoded value using subprocess.Popen in Python?


Can someone tell me how to encode the return statement so that it can decode it. Or whats needs to be changed to get encoded value.

Code

def run_process(cmd_args):
    with subprocess.Popen(cmd_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc:
        return proc.communicate()


res = run_process(cmd_args);
print(res)
print(res.decode("utf-8"))

Output

print(res.decode("utf-8"))
AttributeError: 'tuple' object has no attribute 'decode'

Solution

  • Popen.communicate returns a tuple of (stdout, stderr), so you need to treat the returning value as such:

    stdout, stderr = run_process(cmd_args);
    print(stdout)
    print(stdout.decode("utf-8"))
    

    Please read Popen.communicate's documentation for more details.