Python 子进程输出到 stdout

发布于 2024-11-08 15:52:55 字数 363 浏览 0 评论 0原文

我正在使用 subprocess 模块从 python 运行二进制文件。

为了捕获二进制文件产生的输出,我使用:

proc = subprocess.Popen (command_args, shell=False, stdout=subprocess.PIPE)
out = proc.communicate()[0]
#print the output of the child process to stdout
print (out)

它的作用是在进程执行完成后打印进程的输出。无论如何,我可以在程序执行时将此输出打印到标准输出吗?我真的需要看看输出是什么,因为这些程序可以运行很长时间。

感谢您的帮助。

I am using the subprocess module to run binaries from python.

To capture the output produced by the binary, I am using:

proc = subprocess.Popen (command_args, shell=False, stdout=subprocess.PIPE)
out = proc.communicate()[0]
#print the output of the child process to stdout
print (out)

What this does is print the output of the process AFTER it has finished executing. Is there anyway I can print this output to stdout WHILE the program is executing? I really need to see what the output is because these programs can run for a long time.

Thanks for the help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

月下伊人醉 2024-11-15 15:52:55

只是不要将输出发送到管道:

proc = subprocess.Popen (command_args, shell=False)
proc.communicate()

Simply don't send the output to a pipe:

proc = subprocess.Popen (command_args, shell=False)
proc.communicate()
短叹 2024-11-15 15:52:55

这对我有用:

如果需要在 powershell 中执行命令:

import subprocess

S_V = subprocess.Popen(["powershell.exe", 'your command'   ], stdout=subprocess.PIPE)
out, err = S_V.communicate()
print (out)
print (err )

或者如果需要在 CMD 中执行命令:

name=subprocess.check_output('whoami')  # replace your command with 'whoami'
name=name.decode("utf-8") 
print (name)

注意:whoami 显示用户的用户当前已登录到本地系统。

This work for me:

If need execute command in powershell :

import subprocess

S_V = subprocess.Popen(["powershell.exe", 'your command'   ], stdout=subprocess.PIPE)
out, err = S_V.communicate()
print (out)
print (err )

Or if need execute command in CMD :

name=subprocess.check_output('whoami')  # replace your command with 'whoami'
name=name.decode("utf-8") 
print (name)

Note: whoami Displays user for the user who is currently logged on to the local system .

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文