Store output of subprocess.Popen call in a string

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

    In Python 3.7 a new keyword argument capture_output was introduced for subprocess.run. Enabling the short and simple:

    import subprocess
    
    p = subprocess.run("echo 'hello world!'", capture_output=True, shell=True, encoding="utf8")
    assert p.stdout == 'hello world!\n'
    
    0 讨论(0)
  • 2020-11-22 04:00
     import os   
     list = os.popen('pwd').read()
    

    In this case you will only have one element in the list.

    0 讨论(0)
  • 2020-11-22 04:00
    import subprocess
    output = str(subprocess.Popen("ntpq -p",shell = True,stdout = subprocess.PIPE, 
    stderr = subprocess.STDOUT).communicate()[0])
    

    This is one line solution

    0 讨论(0)
提交回复
热议问题