python : redirected message order

标签 python redirect subprocess

我可以在命令行中使用“>”字符简单地重定向 Python 脚本输出。 但是,如果 Python 脚本具有 subprocess.call(),则会丢失输出行的顺序。

测试.py

import subprocess

print("Message from Python... this should appear at 1st line")
subprocess.call(r"c:\src\python\redirect2\hi.bat")

嗨.bat

@echo off
echo Message from batch file. this should appear at 2nd line.

下面是我期望的消息。

C:\src\python\redirect2>\Python34\python.exe test.py

Message from Python... this should appear at 1st line
Message from batch file. this should appear at 2nd line.

但是,一旦我重定向了它的输出,这些行的顺序就被调换了。

C:\src\python\redirect2>\Python34\python.exe test.py > console.txt

C:\src\python\redirect2>type console.txt
Message from batch file. this should appear at 2nd line.
Message from Python... this should appear at 1st line

有谁知道如何防止这种情况发生? 放置 sleep() 似乎没有帮助。我使用的是 Windows 8.1。

最佳答案

您应该改用 subprocess.Popen,这样您就可以捕获输出。

import subprocess

print("Message from Python... this should appear at 1st line")
p = subprocess.Popen("c:\src\python\redirect2\hi.bat", stdout=subprocess.PIPE)
out, err = p.communicate()

print out

关于 python : redirected message order,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26882050/

相关文章:

python - 尽管在 matplotlib 中设置了不可见轴,但 eps 图像中的幻影轴

apache - .htaccess - 一个特定域的 SSL redicect 条件不起作用

python - 要将 Turbolinks 5 与 Django 一起使用,如何在使用 redirect() 时自动包含 Turbolinks-Location header ?

python - 如何在 Python 中执行复杂的 SoX 命令行字符串

python - pandas - 将带有数组的列拆分为多列并计数值

python - plt.plot 使用元组参数绘制什么?

python - 使用 python 模块子进程的 pg_dump 和 pg_restore 密码

python - 模拟 Ctrl-C 到 python 脚本

python - 如何在第一次出现一个字符时将字符串分成两部分

PHP header ('Location: ' 。 $url) http1.0 对比 http1.1 对比?