Harry
Harry

Reputation: 13

Python execution order using subprocess.call

I have the following code in file abc.py:

import subprocess
def evaluate():
    for i in range(5):
        print("Printing", i)
        subprocess.call(['ls', '-lrt'])
        print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
evaluate()

Now when I call using python abc.py > out.dat, the output file contains the result of 'ls -lrt' five times which is followed by printing statements in the code. Why is it happening so and what should I do if I need to get output as:

printing 0

(results of ls -lrt here)

~~~~~~~~~~~~~~~~~~~~~~~

printing 1

.
.
.

and so on..?

Thank you..

Upvotes: 1

Views: 607

Answers (1)

Alfe
Alfe

Reputation: 59436

You need to flush your stream before you call a subprocess:

import subprocess, sys
def evaluate():
    for i in range(5):
        print("Printing", i)
        sys.stdout.flush()
        subprocess.call(['ls', '-lrt'])
        print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
evaluate()

Flushing takes automatically place line-by-line as long as you write to a terminal (without redirection). Then you do not notice the problem because the print() flushes at the newline.

As soon as you redirect your output to a file the print() statement notices this and flushes automatically only when a certain buffer is full (and at termination time).

The subprocess (ls) does the same but uses its own buffer. And it terminates first, so its output is in the file first.

Upvotes: 2

Related Questions