我正在使用Python子进程函数,因为我想实时读取命令的输出。
但我希望在流程结束后,作为流输出写入的所有内容都完全返回到对象。
import subprocess
import shlex
def run_command(command):
process = subprocess.Popen(str.split(command), stdout=subprocess.PIPE, stderr = subprocess.PIPE, encoding="utf-8", shell=True)
while True:
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output:
print(output.strip())
out, err = process.communicate()
return (process.returncode, out, err)
command_output = run_command("ping 8.8.8.8")
print(command_output)
实际结果:
Pinging 8.8.8.8 with 32 bytes of data:
Reply from 8.8.8.8: bytes=32 time=12ms TTL=57
Reply from 8.8.8.8: bytes=32 time=15ms TTL=57
Reply from 8.8.8.8: bytes=32 time=15ms TTL=57
Reply from 8.8.8.8: bytes=32 time=16ms TTL=57
Ping statistics for 8.8.8.8:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 12ms, Maximum = 16ms, Average = 14ms
(0, '', '')
我只得到已完成进程的代码状态。 标准输出为空,但应包含已处理命令的所有输出。
我使用 Python 3.7.4
我不知道该怎么办。
您无法多次从管道读取,因此在完成后调用process.communicate()
将不允许再次读取stdout
。
您应该简单地将您在字符串中读取的所有输出。
def run_command(command):
process = subprocess.Popen(str.split(command), stdout=subprocess.PIPE, stderr = subprocess.PIPE, encoding="utf-8", shell=True)
all_output = ''
while True:
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output:
all_output += output
print(output.strip())
out, err = process.communicate()
return (process.returncode, all_output, err)