Search code examples
pythonpython-datetime

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

  • 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.)