从Python运行外部命令。然后在屏幕上显示输出并同时获得输出

时间:2017-09-06 18:07:59

标签: python subprocess

我知道从Python运行外部命令并在屏幕上显示输出很容易。例如:(它将仅在屏幕上显示输出

import subprocess
subprocess.Popen(['dir'])

我也知道我们可以从Python运行外部命令并获取输出。例如:(它将将输出存储为变量 out 中的字符串,将不再显示屏幕上的输出)

import subprocess
result = subprocess.Popen(['dir'], stdout=subprocess.PIPE)
out = result.stdout.read()

我的问题是:有没有办法在屏幕上显示输出并以变量同时存储和输出?换句话说,当我运行代码时,外部命令输出将显示在屏幕上。同时,代码中的变量可以使输出显示在屏幕上。

更新:我发现如果我在stdout=subprocess.PIPE中包含subprocess.Popen,它将不会在屏幕上显示任何内容(Windows命令提示符)。

相关问题:

live output from subprocess command

Output of subprocess both to PIPE and directly to stdout

2 个答案:

答案 0 :(得分:1)

如果您需要Popen的实时输出,您可以使用类似的内容( Windows 平台根据您的last comment):

字节流

import sys, subprocess
out=b''
result = subprocess.Popen(['cmd', '/c', 'dir /B 1*.txt'], stdout=subprocess.PIPE, 
    universal_newlines=False)
for s_line in result.stdout:
    #Parse it the way you want
    out += s_line
    print( s_line.decode(sys.stdout.encoding).replace('\r\n',''))

# debugging output
print(out.decode(sys.stdout.encoding))

文字流

import subprocess
out=''
result = subprocess.Popen(['cmd', '/c', 'dir /B 1*.txt'], stdout=subprocess.PIPE, 
    universal_newlines=True)
for s_line in result.stdout:
    #Parse it the way you want
    out += s_line
    print( s_line.rstrip())

# debugging output
print(out)

后一段代码段输出

>>> import subprocess
>>> out=''
>>> result = subprocess.Popen(['cmd', '/c', 'dir /B 1*.txt'], stdout=subprocess.PIPE,
...     universal_newlines=True)
>>> for s_line in result.stdout:
...     #Parse it the way you want
...     out += s_line
...     print( s_line.rstrip())
...
1.325.txt
1049363a.txt
1049363b.txt
1051416.txt
1207235log.txt
>>> print(out)
1.325.txt
1049363a.txt
1049363b.txt
1051416.txt
1207235log.txt

>>>

答案 1 :(得分:1)

使用| tee(在Windows平台上,使用Powershell):

import subprocess

# Run command in powershell and redirect it by | tee to a file named out.txt 
result = subprocess.Popen(['powershell', command, '|', 'tee', 'out.txt'])

# Get standard output
f = open('out.txt')
out = f.read()
f.close()

通过这种方式,屏幕将在PowerShell终端上显示输出,输出也将存储在 out 中。