Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : redirected message order

I can redirect Python script output simply with ">" character in command line. However, if Python script has subprocess.call(), the order of output lines is missed.

test.py

import subprocess

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

hi.bat

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

Below is the message I expect.

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.

However, once I redirect its output, the order of these lines got swapped.

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

Does anyone know how to prevent this ? Putting sleep() doesn't seem help. I'm using Windows 8.1.

like image 233
Tony Avatar asked Jan 17 '26 10:01

Tony


1 Answers

you should use subprocess.Popen instead, so you can capture the output.

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
like image 142
adrianX Avatar answered Jan 20 '26 00:01

adrianX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!