如何将进度状态写入文件

时间:2014-02-16 06:56:30

标签: python

我想打印一个进展状态。我使用'\ r'来实现它。以下是我的代码

#test.py
import sys

print("beg")
for i in range(10000):  
    sys.stdout.write("\r%% %d"%((i+1)*100.0/10000))
    sys.stdout.flush()
print("\nend")

它适用于终端。但是当我重定向输出时,它无法正常工作

python test.py > log.txt

来自mhlester的正确解析

import sys

tty = sys.stdout.isatty()
print('beg')
if not tty:  
    position = sys.stdout.tell()                # get position
for i in range(10000):
    if tty:                                 # use falsetru's answer here
        sys.stdout.write('\r%% %d'%((i+1)*100.0/10000))# as you were before
    else:
        print('of')
        sys.stdout.seek(position)                  # or seek to position
        sys.stdout.write('%% %d'%((i+1)*100.0/10000))
    sys.stdout.flush()
print('\nend')

2 个答案:

答案 0 :(得分:1)

\r写入文件的行为与将其写入终端的行为不同。

它将字节13(0x0d)写入文件而不是移动光标。

你最好检查流是否是tty,然后根据它做不同的事情。

>>> sys.stdout.isatty()
True

答案 1 :(得分:1)

它不适用于stdout,但如果您写入文件,它将起作用。您需要\r到文件中的正确位置,而不是seek()。要找出您在文件中的位置,请使用tell()

    sys.stdout.write('beg')
    position = sys.stdout.tell()                # get position
    for i in range(10000):
        if tty:                                 # use falsetru's answer here
            print '\r',                         # as you were before
        else:
            out.seek(position)                  # or seek to position
        out.write('%% %d'%((i+1)*100.0/10000))
        out.flush()
    out.write('\nend')

编辑双向工作