Python3:print(somestring,end ='\ r',flush = True)没有显示任何内容

时间:2016-01-09 05:29:08

标签: python pycharm python-3.4

我正在编写一个进度条,因为How to animate the command line?建议。我使用Pycharm并在运行工具窗口中运行此文件。

import time
def show_Remaining_Time(time_delta):
    print('Time Remaining: %d' % time_delta, end='\r', flush=True)

if __name__ == '__main__':
    count = 0
    while True:
        show_Remaining_Time(count)
        count += 1
        time.sleep(1)

但是,如果我运行此.py文件,则代码不显示任何内容。我做错了什么?

我尝试了Jogger的建议,但如果我使用print函数,它仍然无效。

但是,以下脚本按预期工作。

import time
import sys
def show_Remaining_Time(time_delta):
    sys.stdout.write('\rtime: %d' % time_delta) # Doesn't work if I use 'time: %d\r'
    sys.stdout.flush()
if __name__ == '__main__':
    count = 0
    while True:
        show_Remaining_Time(count)
        count += 1
        time.sleep(1)

我现在有2个问题:

  1. 为什么stdout有效但打印()没有。

  2. 为什么How to animate the command line?建议将\r追加到最后,而我必须在我的情况下在开头写一下?

2 个答案:

答案 0 :(得分:0)

问题是最后的'\ r'清除了你刚刚打印的那条线,那该怎么办?

import time
def show_Remaining_Time(time_delta):
    print("\r")
    print('Time Remaining: %d' % time_delta, flush=True)

if __name__ == '__main__':
    count = 0
    while True:
        show_Remaining_Time(count)
        count += 1
        time.sleep(1)

这样,您首先清除该行,然后打印所需的显示,并在睡眠期间将其保留在屏幕中。

答案 1 :(得分:0)

此方法可以在同一命令行中打印:

import time
def show_Remaining_Time(time_delta):
     print(' \r%d:Time Remaining' % time_delta, end = '',flush=False)

if __name__ == '__main__':
    count = 0
    while True and count < 10:
        show_Remaining_Time(count)
        count += 1
        time.sleep(1)