简体   繁体   English

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

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

I'm writing a progress bar as this How to animate the command line? 我正在编写一个进度条, 如何为命令行设置动画? suggests. 提示。 I use Pycharm and run this file in Run Tool Window. 我使用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)

However, the code displays nothing if I run this .py file. 但是,如果我运行此.py文件,代码将不显示任何内容。 What am I doing wrong? 我究竟做错了什么?


I tried Jogger's suggest but it's still not working if I use print function. 我试过Jogger的建议,但如果我使用print功能它仍然无法正常工作。

However the following script works as expected. 但是,以下脚本按预期工作。

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)

I have 2 questions now: 我现在有两个问题:

  1. Why stdout works but print() not. 为什么stdout工作但print()没有。

  2. Why the How to animate the command line? 为什么如何设置命令行的动画? suggests append \\r to the end while I have to write it at the start in my case? 建议将\\r添加到最后,而我必须在我的情况下在开头写它?

The problem is that the '\\r' at the end clears the line that you just printed, what about? 问题是最后的'\\ 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)

In this way, you clear the line first, and then print the desired display, keeping it in screen for the duration of the sleep. 通过这种方式,您首先清除该行,然后打印所需的显示,在睡眠期间将其保留在屏幕中。

This method can print in the same command line: 此方法可以在同一命令行中打印:

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