1

I'm trying to get all of my script's output to be on a single line, but the output won't always be the same length, so before I print the next line I "wipe" it by printing a line of white space.

Sometimes the output flickers now due to the white space overwriting it. What's the best way to buffer the output and then write it all at once?

while(True):
    print(' ' * width, end='\r')
    print(f'Mouse position: {mouse.position}', end='\r', flush=True)
    time.sleep(.05)

2 Answers 2

2

Don't overwrite the previous text with spaces before printing the next. There's no need to erase the whole line; printing the new text will cover most of the previous line. Just print enough spaces at the end to erase any extra characters that might be there from the previous output. Figure out the difference between longest output you could get and the shortest, and print that number of spaces. Say the difference is six; add six spaces to the end, like so:

while True:
    print(f'Mouse position: {mouse.position}      ', end='\r', flush=True)
    time.sleep(.05)

This tip brought to you by a former Apple II BASIC programmer, who needed his text not to flicker... on a 1 MHz 8-bit processor.

Sign up to request clarification or add additional context in comments.

Comments

1

I believe you are asking about padding, buffering is something entirely different

while(True):
    print(f'Mouse position: {mouse.position:>15}', end='\r', flush=True)
    time.sleep(.05)

would force it to always write the coords using 15 character spaces... you could put the coords on the left using < instead of >, and if you wanted to center it you could use ^ ... see also :https://pyformat.info/#string_pad_align

1 Comment

Thanks! I ended up left aligning it with 15 characters and I got the intended effect.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.