Python3:print(somestring,end='\r',flush=True) 什么也没显示 [英] Python3: print(somestring,end='\r', flush=True) shows nothing

查看:25
本文介绍了Python3:print(somestring,end='\r',flush=True) 什么也没显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个进度条作为这个 如何为命令设置动画线? 建议.我使用 Pycharm 并在运行工具窗口中运行此文件.

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.

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 文件,代码将不会显示任何内容.我做错了什么?

However, the code displays nothing if I run this .py file. What am I doing wrong?

我尝试了 Jogger 的建议,但如果我使用 print 功能,它仍然不起作用.

I tried Jogger's suggest but it's still not working if I use print function.

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

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)

我现在有两个问题:

  1. 为什么 stdout 有效而 print() 无效.

  1. Why stdout works but print() not.

为什么要如何为命令行设置动画? 建议将 \r 附加到最后,而我必须在开始时编写它?

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?

import time
def show_Remaining_Time(time_delta):
    print("\r", end='')
    print('Time Remaining: %d' % time_delta, end='', 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.

注意:按照注释中的建议,修改了上面的代码以添加 end='',以便代码在某些平台上正常工作.感谢其他读者帮助撰写更完整的答案.

NOTE: The code above was modified to add the end='' as suggested in the comments for the code to work properly in some platforms. Thanks to other readers for helping to craft a more complete answer.

这篇关于Python3:print(somestring,end='\r',flush=True) 什么也没显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆