繁体   English   中英

如何等待子进程完成,存储其输出并在输出中添加前缀(没有新行)?

[英]How do I wait for a subprocess to finish, store it's output and add a prefix (without a new line) to the output?

我有一个使用subprocess.call([...])方法调用外部命令的Python(3)脚本:

import subprocess

print("Prefix: ")
subprocess.call(["cmd", "--option", "filename.x"])

该命令执行时没有任何错误,但问题是输出。

输出不是“统一”的 ,有时程序会输出:

Program output...
Prefix:

其他时间的输出将是:

Prefix:
Program output....

我正在寻找的结果是:

Prefix: Program output...

我知道,为了达到这个结果,我需要等待子进程来完成,存储它的输出,然后打印前缀(无\\n )与子输出之后,我只是想不通怎么办它。

谢谢。

首先,您需要导入sys模块,以便可以使用sys.stdoutwriteflush方法。

import sys

您还需要导入子流程模块,以便可以使用subprocess.check_output方法。

import subprocess

使用sys.stdout.write代替print

sys.stdout.write("Prefix: ")

然后,您需要将subprocess.call替换为subprocess.check_output ,该命令将运行给定命令并等待输出。

response = subprocess.check_output(["cmd", "--option", "filename.x"])

注意:您需要解码响应,因为它是一个字节对象而不是字符串。

sys.stdout.write(response.decode("UTF-8"))

最后,您需要刷新输出:

sys.stdout.flush()

这是最终结果:

import sys, subprocess
sys.stdout.write("Prefix: ")
response = subprocess.check_output(["cmd", "--option", "filename.x"])
sys.stdout.write(response.decode("UTF-8"))
sys.stdout.flush()

祝你好运,希望没有人像我一样在这个问题上绊倒了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM