Store output of subprocess.Popen call in a string

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

    subprocess.Popen: http://docs.python.org/2/library/subprocess.html#subprocess.Popen

    import subprocess
    
    command = "ntpq -p"  # the shell command
    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None, shell=True)
    
    #Launch the shell command:
    output = process.communicate()
    
    print output[0]
    

    In the Popen constructor, if shell is True, you should pass the command as a string rather than as a sequence. Otherwise, just split the command into a list:

    command = ["ntpq", "-p"]  # the shell command
    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None)
    

    If you need to read also the standard error, into the Popen initialization, you can set stderr to subprocess.PIPE or to subprocess.STDOUT:

    import subprocess
    
    command = "ntpq -p"  # the shell command
    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    
    #Launch the shell command:
    output, error = process.communicate()
    

提交回复
热议问题