'Is it possible to update a line of already printed text in python?
I am working on a text based operating system in Python and I am wondering if it would be possible to update an already printed string on the same line. There doesn't seem to be anything on this other than this which doesn't really answer my question.
What I was thinking was something like:
Fri 13 May 6:00:34 PM
Then updating the same text with:
Fri 13 May 6:00:35 PM
This is a portion of my current code:
def desktop():
now = datetime.today()
print(f"{now:%c}")
help = input(bcolors.OKCYAN + '''
/help for a list of commands
''')
if help == '/help':
#This goes to a function that shows a list of possible commands
get_help()
else:
pass
Is this even possible? If so how?
Many Thanks,
mrt
Solution 1:[1]
You might be able to do this in a limited way by writing out '\b'
to erase and rewrite.
import sys
def foo()
sys.stdout.write('foo')
sys.stdout.flush()
sys.stdout.write('\b\b\b')
sys.stdout.write('bar')
sys.stdout.flush()
I'm doing a similar thing on the command line, on a Mac. And this has worked so far, as long as I haven't already written out a newline. (Hence sys.stdout.write
and not print
.)
Solution 2:[2]
The short answer, no. It's going to be extremely difficult, if not impossible, to do this using print functions for anything other than the last printed line, which seems to be the case here.
You could, however, look into TUI (Textual User Interfaces), such as https://github.com/Textualize/textual or https://github.com/bczsalba/pytermgui .
Solution 3:[3]
You can have a look at this. Basically, you overwrite the previous line. I am not sure if this is what you are looking for.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Paul |
Solution 2 | Dominik Sta?czak |
Solution 3 | Amer |