我可以在命令行中使用“>”字符简单地重定向 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/