Store output of subprocess.Popen call in a string

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

    The following captures stdout and stderr of the process in a single variable. It is Python 2 and 3 compatible:

    from subprocess import check_output, CalledProcessError, STDOUT
    
    command = ["ls", "-l"]
    try:
        output = check_output(command, stderr=STDOUT).decode()
        success = True 
    except CalledProcessError as e:
        output = e.output.decode()
        success = False
    

    If your command is a string rather than an array, prefix this with:

    import shlex
    command = shlex.split(command)
    

提交回复
热议问题