Reputation: 261
I have a script that simply outputs log events formatted in json to the screen line by line. One line equals one json log event. I usually simply append the results to a file to hold onto them when I need to (./script.py >> json.logs).
This script can take a while depending on the input, and I'd like to add a simple progress bar or number to the bottom of the console as it's working. However, I think this will also be written to the log file if I append like normal and I do not want that.
What is the normal way to approach printing something to the console that will not be appended to stdout or >>? Also, if I'm just simply printing the results to the screen instead of logging them to a file, I need the status bar to not make a mess in the screen as well (or rather, to only ever show at the bottom of the console screen).
Upvotes: 1
Views: 948
Reputation: 2003
The idea is to use the stderr (import sys; sys.stderr.write('the bar')
you could use print ('barstuff', file=sys.stderr)
if you are using python3). This works fine if you want to save the stdout in a file while having the bar in the screen. To have the bar always at the bottom of the screen, looks like quite complicated: you should know what is the height of the screen and, I think, this could be almost impossible from python.
Probably, with some magic, you could be able to print the bar at the beginning of the screen and a given number of lines below it using the \r to rewrite on the old strings.
Upvotes: 1
Reputation: 1857
Using >>
will by default only pipe STDOUT to the file, so if you print to STDERR, it won't go to the log. For example:
import sys
print("something") # this will go to json.logs
print("something else", file=sys.stderr) # this won't go to json.logs unless you specifically tell it to
As for making the bar itself, either look at something like tqdm or if you specifically want the bar to appear at the bottom of the window, you may have to roll your own solution with curses. Or just do something simple, like print one asterisk at a time.
Upvotes: 2