Store output of subprocess.Popen call in a string

前端 未结 15 2490
一个人的身影
一个人的身影 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:51

    This works perfectly for me:

    import subprocess
    try:
        #prints results and merges stdout and std
        result = subprocess.check_output("echo %USERNAME%", stderr=subprocess.STDOUT, shell=True)
        print result
        #causes error and merges stdout and stderr
        result = subprocess.check_output("copy testfds", stderr=subprocess.STDOUT, shell=True)
    except subprocess.CalledProcessError, ex: # error code <> 0 
        print "--------error------"
        print ex.cmd
        print ex.message
        print ex.returncode
        print ex.output # contains stdout and stderr together 
    

提交回复
热议问题