3

I would like to know the logic behind the order of the outputs in Python 3. For example:

test.py:

import sys
print("my stdout", file=sys.stdout)
print("my stderr", file=sys.stderr)

I want both outputs in the same file.

I run the code with this command:

python3 test.py 1>all_outputs.txt2>&1

I was expecting to obtain the following output:

all_outputs.txt:

my stdout
my stderr

But the result in:

my stderr
my stdout

So why did the error come in first ?

Mike Delta
  • 726
  • 2
  • 16
  • 32

1 Answers1

1

As suggested by Patrick-Haugh in the comments to include flush=True parameter to print() functions, and borrowing the bash syntax from answer in How can I redirect and append both stdout and stderr to a file with Bash?:

import sys
print("my stdout", file=sys.stdout, flush=True)
print("my stderr", file=sys.stderr, flush=True)

then:

$ python3 test.py > all_outputs.txt 2>&1
$ cat all_outputs.txt 
my stdout
my stderr