0

I have a Python file like this:

#!/usr/local/bin/python3.9
print("Writing to file...")
print({"test": 1})

I'm running it from the shell like this:

./script.py > output.json

Which writes the following to output.json:

Writing to file...
{'test': 1}

The behaviour I want to achieve is for the first print statement to be printed to the console only, and for the second print statement to be written to the file. i.e. I want some things to be printed normally, and some things to be written to a file. Like this:

#!/usr/local/bin/python3.9
print("Writing to file...")  # only prints to console
print({"test": 1})  # only writes to output.json

How can I modify my code to achieve this? It's important that the shell command is unchanged.

K--
  • 594
  • 1
  • 8
  • 20
  • 1
    One easy way is to write your status stuff to `sys.stderr`, like `print("Writing to file...",file=sys.stderr)`. You'll have to `import sys`, of course. – Tim Roberts Mar 30 '21 at 19:00

1 Answers1

2

The simplest solution is to make the stuff you want to go to the shell go to stderr, not stdout (the default target for print):

#!/usr/local/bin/python3.9

import sys

print("Writing to file...", file=sys.stderr)  # prints to console because stderr not redirected
print({"test": 1})  # writes to output.json because stdout is redirected

The user could independently redirect stderr if they like, but the example command would leave it going to the terminal. This is typically how programs split up "debug output" from "productive output" when not explicitly writing "productive output" to a specific file.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271