Store output of subprocess.Popen call in a string

前端 未结 15 2226
一个人的身影
一个人的身影 2020-11-22 03:23

I\'m trying to make a system call in Python and store the output to a string that I can manipulate in the Python program.

#!/usr/bin/python
import subprocess         


        
15条回答
  •  长发绾君心
    2020-11-22 03:55

    This was perfect for me. You will get the return code, stdout and stderr in a tuple.

    from subprocess import Popen, PIPE
    
    def console(cmd):
        p = Popen(cmd, shell=True, stdout=PIPE)
        out, err = p.communicate()
        return (p.returncode, out, err)
    

    For Example:

    result = console('ls -l')
    print 'returncode: %s' % result[0]
    print 'output: %s' % result[1]
    print 'error: %s' % result[2]
    

提交回复
热议问题