繁体   English   中英

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

[英]Python3: print(somestring,end='\r', flush=True) shows nothing

我正在编写一个进度条, 如何为命令行设置动画? 提示。 我使用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)

我现在有两个问题:

  1. 为什么stdout工作但print()没有。

  2. 为什么如何设置命令行的动画? 建议将\\r添加到最后,而我必须在我的情况下在开头写它?

问题是最后的'\\ 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)

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

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

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM