Home >Backend Development >Python Tutorial >How Can I Overwrite Previous Output to Standard Output (Stdout) in Python?

How Can I Overwrite Previous Output to Standard Output (Stdout) in Python?

DDD
DDDOriginal
2024-12-28 20:25:11431browse

How Can I Overwrite Previous Output to Standard Output (Stdout) in Python?

Overwriting Previous Output to Stdout

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.

Carriage Return (r)

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()

Comma at the End of Print Statement

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

Clear to End of Line (x1b[1K)

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()

Disabling Line Wrapping

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn