In many programming scenarios, it is necessary to modify or update the output displayed on the terminal. This article explores methods to overwrite the previous print to stdout, replacing it with updated values on the same line.
Python provides the r (carriage return) character to move the cursor back to the start of the current line without advancing to the next one. By using r, you can overwrite the previous print statement:
# Python 3 for x in range(10): print(x, end='\r') print() # Python 2.7 from __future__ import print_function for x in range(10): print(x, end='\r') print()
In Python 2, a comma at the end of a print statement prevents it from advancing to the next line, allowing for overwriting:
# Python 2 for x in range(10): print '{0}\r'.format(x), print
When the new line of text is shorter than the previous one, you can use x1b[1K (clear to end of line) to clear the remaining characters:
for x in range(75): print('*' * (75 - x), x, end='\x1b[1K\r') print()
By default, Python wraps lines that exceed the terminal width. To prevent this and ensure that consecutive characters overwrite the previous line, disable line wrapping with x1b[7l:
print('\x1b[7l', end='') # Disable line wrapping for x in range(50): print(x, end='\r') print('\x1b[7h', end='') # Re-enable line wrapping
Note: Always re-enable line wrapping after disabling it to avoid leaving the terminal in a broken state.
The above is the detailed content of How Can I Overwrite Previous Output to Standard Output (Stdout) in Python?. For more information, please follow other related articles on the PHP Chinese website!