Store output of subprocess.Popen call in a string

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

    For python 3.5 I put up function based on previous answer. Log may be removed, thought it's nice to have

    import shlex
    from subprocess import check_output, CalledProcessError, STDOUT
    
    
    def cmdline(command):
        log("cmdline:{}".format(command))
        cmdArr = shlex.split(command)
        try:
            output = check_output(cmdArr,  stderr=STDOUT).decode()
            log("Success:{}".format(output))
        except (CalledProcessError) as e:
            output = e.output.decode()
            log("Fail:{}".format(output))
        except (Exception) as e:
            output = str(e);
            log("Fail:{}".format(e))
        return str(output)
    
    
    def log(msg):
        msg = str(msg)
        d_date = datetime.datetime.now()
        now = str(d_date.strftime("%Y-%m-%d %H:%M:%S"))
        print(now + " " + msg)
        if ("LOG_FILE" in globals()):
            with open(LOG_FILE, "a") as myfile:
                myfile.write(now + " " + msg + "\n")
    

提交回复
热议问题