只需用\r
不會在這種情況下工作,因爲這將返回到行的開始,所以你必須重新打印整條生產線。另外,在某些系統(包括Windows,我認爲)Python的print
語句(3+中的函數)將\r
解釋爲換行符。我相信這個代碼應該是是系統無關的。
import sys, time
with open('names.txt', 'r') as names:
prev_len = 0
for name in names:
sys.stdout.write('\r' + ' ' * prev_len)
sys.stdout.flush()
output_string = '\rname={}'.format(name.strip())
prev_len = len(output_string)
sys.stdout.write(output_string)
sys.stdout.flush()
time.sleep(0.3)
print
您也可以使用\b
,它通常會將光標向後移動一個空格。
正如你指出,這是必要的覆蓋用空格先前打印線,這意味着要記住以前的線的長度是必要的。我想,把這個狀態封裝在一個對象中是有意義的。這裏有一個比上面那個更清潔的解決方案使用的策略:
import sys, time
class LineUpdater(object):
def __init__(self, outfile=None):
self.prev_len = 0
self.outfile = sys.stdout if outfile is None else outfile
def write(self, line):
line = line.strip()
output = '\r{:<{width}}'.format(line, width=self.prev_len)
self.prev_len = len(line)
self.outfile.write(output)
self.outfile.flush()
with open('names.txt', 'r') as names:
out = LineUpdater()
for name in names:
out.write('name={}'.format(name))
time.sleep(0.3)
print
的建議只是爲了澄清,要_overwrite_行的一部分,是正確? – senderle