簡體   English   中英

sys.stdout.write \\ r回車,如何覆蓋所有字符?

[英]sys.stdout.write \r carriage, how to overwrite all characters?

我正在使用itertools.cycle,正在使用一個簡單的列表作為輸入。 然后,我編寫一個while循環,當我遍歷它們時,我想基本上用每種顏色覆蓋我的輸出。 sys.stdout.write('\\r' + colors)行不會覆蓋所有字符,僅覆蓋下一個顏色的字符串的長度。 最后,每次迭代之間有0.5秒的延遲。

import itertools
import time
colors = ['green', 'yellow', 'red']
traffic_light = itertools.cycle(colors)
while True:
    sys.stdout.write('\r' + next(traffic_light))
    sys.stdout.flush()
    time.sleep(.5)

當我在循環中到達“黃色”時,當打印較短的“綠色”和“紅色”字符串時,我留下“ w”或“ low”。 我的輸出看起來像這樣(在打印“ yellow”時的第一個循環之后)。

redlow
greenw
yellow

我可以用'\\r'完全覆蓋輸出嗎?

回車符'\\r'會將光標發送到該行的開頭,在此處可以覆蓋現有文本。 您可以將其與序列CSI K結合使用,該序列將從當前光標擦除到行尾。

只需將\\r替換為\\r\\x1b[K 請參閱ANSI轉義代碼

import itertools
import sys
import time
colors = ['green', 'yellow', 'red']
traffic_light = itertools.cycle(colors)
while True:
    sys.stdout.write('\r\x1b[K' + next(traffic_light))
    sys.stdout.flush()
    time.sleep(.5)

試用以下其他轉義序列:

# Add color
colors = ['\x1b[32mgreen', '\x1b[33myellow', '\x1b[31mred']

請注意此技術的局限性...如果終端足夠短,以至於您的文字不能換行,則每次打印時程序都會向前移動一行。 如果您需要更強大的功能, curses可為您提供更多功能,但在Windows上無法立即使用。

您可以計算顏色字符串的最大寬度,然后使用str.ljust在輸出中填充足夠的空間以填充到最大寬度:

import itertools
import time
import sys
colors = ['green', 'yellow', 'red']
traffic_light = itertools.cycle(colors)
max_width = max(map(len, colors))
while True:
    sys.stdout.write('\r' + next(traffic_light).ljust(max_width))
    sys.stdout.flush()
    time.sleep(.5)

創建一個格式字符串,該字符串左對齊至最大寬度。

import itertools
import time

colors = ['green', 'yellow', 'red']
fmt = f'\r{{:<{max(map(len, colors))}}}' # fmt = '{:<7}'

for color in itertools.cycle(colors):
    print(fmt.format(color), end='') # if needed add: flush=True
    time.sleep(.5)

在3.6之前的版本中使用fmt = '\\r{{:<{}}}'.format(max(map(len, colors)))

或者,使用.ljust()字符串方法:

import itertools
import time

colors = ['green', 'yellow', 'red']
width = max(map(len, colors))

for color in itertools.cycle(colors):
    print('\r' + color.ljust(width), end='') # if needed add: flush=True
    time.sleep(.5)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM