简体   繁体   English

python中的倒数计时器实际上不显示任何内容

[英]Countdown timer in python does not actually display anything

import time


def countdown(duration):
    while duration > 0:
        mins, seconds = divmod(duration, 60)
        timer = '{:02d}:{:02d}'.format(mins, seconds)
        print(timer, end='\r')
        time.sleep(1)
        duration -= 1
    print("Time's up!")


countdown(int(input(": ")))

I wanted to make a timer on python and learned how to make one as well.我想在 python 上制作一个计时器并学习如何制作一个。 I understood how everything worked but for some reason when I ran the code the timer didn't actually show up at all.我理解一切是如何工作的,但是由于某种原因,当我运行代码时,计时器实际上根本没有出现。 After the cursor blinks for how long I told the timer to run, it prints the "Time's up" prompt without ever showing the timer.在光标闪烁了多长时间我告诉计时器运行后,它会打印“时间到”提示,而没有显示计时器。 The duration to wait is correct though, so the timer works, it just doesn't show up.等待的持续时间是正确的,所以计时器工作,它只是不显示。

You said in your comment that you're running the code on PyCharm.您在评论中说您正在 PyCharm 上运行代码。 That is the problem.那就是问题所在。 Your code runs successfully in Linux and Windows;您的代码在 Linux 和 Windows 中成功运行; I just tried.我刚试过。 However, in PyCharm, it does not show any output.但是,在 PyCharm 中,它不显示任何输出。 This is dependent on PyCharm's way to handle carriage returns ("\\r") .这取决于 PyCharm 处理回车("\\r") More information here , it's for YouTrack but applies also to PyCharm.此处的更多信息适用于 YouTrack,但也适用于 PyCharm。

Two ways to fix this:解决此问题的两种方法:

  • change your print(timer, end='\\r') line to print(f'\\r{timer}', end='') (move carriage return to the beginning of print and remove the newline from the print)将您的print(timer, end='\\r')行更改为print(f'\\r{timer}', end='') (将回车移到打印的开头并从打印中删除换行符)
  • Enable "Emulate terminal in output console" in Run/Debug configuration (Edit configurations...) in your PyCharm.在 PyCharm 的运行/调试配置(编辑配置...)中启用“在输出控制台中模拟终端”。

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

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