简体   繁体   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?

I have a Python(3) script that's calling an external command using the subprocess.call([...]) method: 我有一个使用subprocess.call([...])方法调用外部命令的Python(3)脚本:

import subprocess

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

The command executes without any errors but the problem is the output. 该命令执行时没有任何错误,但问题是输出。

The output isn't "uniform" and sometimes the program will output: 输出不是“统一”的 ,有时程序会输出:

Program output...
Prefix:

And other times the output will be: 其他时间的输出将是:

Prefix:
Program output....

The result I'm looking for is: 我正在寻找的结果是:

Prefix: Program output...

I know that in order to achieve this result I need to wait for the subprocess to finish, store it's output and then print the prefix (without \\n ) with the subprocess' output after it, I just can't figure out how to do it. 我知道,为了达到这个结果,我需要等待子进程来完成,存储它的输出,然后打印前缀(无\\n )与子输出之后,我只是想不通怎么办它。

Thanks. 谢谢。

First you need to import the sys module, so you can use sys.stdout 's write and flush methods. 首先,您需要导入sys模块,以便可以使用sys.stdoutwriteflush方法。

import sys

You'll also need to import the subprocess module so you can use the subprocess.check_output method. 您还需要导入子流程模块,以便可以使用subprocess.check_output方法。

import subprocess

Use sys.stdout.write instead of print : 使用sys.stdout.write代替print

sys.stdout.write("Prefix: ")

Then you'll need to replace subprocess.call with subprocess.check_output , which runs the given command and waits for the output. 然后,您需要将subprocess.call替换为subprocess.check_output ,该命令将运行给定命令并等待输出。

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

NOTE: you need to decode the response because it's a bytes object and not a string. 注意:您需要解码响应,因为它是一个字节对象而不是字符串。

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

And finally you need to flush the output: 最后,您需要刷新输出:

sys.stdout.flush()

Here is the final result: 这是最终结果:

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()

Good luck, hopefully no one else will stumble on this question like I did. 祝你好运,希望没有人像我一样在这个问题上绊倒了。

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

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