Store output of subprocess.Popen call in a string

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

    The accepted answer is still good, just a few remarks on newer features. Since python 3.6, you can handle encoding directly in check_output, see documentation. This returns a string object now:

    import subprocess 
    out = subprocess.check_output(["ls", "-l"], encoding="utf-8")
    

    In python 3.7, a parameter capture_output was added to subprocess.run(), which does some of the Popen/PIPE handling for us, see the python docs :

    import subprocess 
    p2 = subprocess.run(["ls", "-l"], capture_output=True, encoding="utf-8")
    p2.stdout
    

提交回复
热议问题