Python : redirected message order
Question: 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.


Answer: 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
    

