Execute python command and shell command (using subprocess) sequentially -


i puzzled order of execution of python command , shell command (from subprocess).

for example, i've got simple code:

import subprocess import shlex  command="echo 'test'" arg=shlex.split(command)  open("out.txt", "w") f:     f.write("line1\n")     subprocess.call(arg, stdout=f)     f.write("line3\n") 

i expect out.txt be:

line1 test line3 

however, actual out.txt is:

test line1 line3 

could explain reason? thank you.

apparently, pythons file object performs buffering before output written underlying file descriptor (via write() system call). line1 ends in buffer not yet written file. subprocess inherits file descriptor has not yet been written to, writes line test, , python writes line3 buffer , flushes line1 , line3 file descriptor.

to work around this, flush file before calling subprocess:

f.write("line1\n") f.flush() subprocess.call(arg, stdout=f) f.write("line3\n") 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -