【问题标题】:Using sleep() while printing in python3在 python3 中打印时使用 sleep()
【发布时间】:2018-01-25 15:26:37
【问题描述】:

我在编程时遇到问题。我试图在 print() 中使用 sleep()。输入是:

print(f'New year in 5{sleep(1)}.4{sleep(1)}.3{sleep(1)}.2{sleep(1)}.1{sleep(1)}. NEW YEAR!')

输出是:

New year in 5None.4None.3None.2None.1None. NEW YEAR!

延迟发生在屏幕打印之前。 我正在使用最新版本的python。 我会等待答案。

【问题讨论】:

标签: python-3.x printing sleep


【解决方案1】:

尝试使用time.sleep(1)(以模块点为前缀)而不是仅使用sleep(1)

如果您只是调用sleep(1),您的脚本将搜索本地定义函数,而不是time模块中定义的函数。

【讨论】:

  • 在你的答案中添加支持链接总是有帮助的。还有一些漂亮的格式可以方便阅读并突出重要点。
【解决方案2】:

可以使用end 属性调用打印。默认值为换行符,但您可以选择只放一个空格。

print('New year in 5', end=' ')

所以您打印的下一个内容将在同一行。

这允许您将睡眠功能移到打印之外。

print('New year in 5', end=' ')
sleep(1)
print('4', end=' ')
sleep(1)
print('3', end=' ')
# ...

【讨论】:

    【解决方案3】:

    您的代码没有按预期工作,因为传递给打印函数的所有对象都被一次性解析和打印。

    因此,当您通过多个 sleep() 时,它们都已编译,并且有一个初始等待,最后您的消息被打印出来了..

    结果中的 None 是 time.sleep() 函数的返回

    解决方案: 实现倒计时功能 确保每次都打印到同一行,唯一的变化是时间。这是通过在 python3 打印函数中使用 '\r' 和 end="" 来实现的

    但是有一个小问题,你的时间中的位数减少了一个,这可以通过用所有空格替换现有的打印行来解决

    #!/usr/bin/python3
    import time
    def countdown(start):
        while start > 0:
            msg = "New year starts in: {} seconds".format(start)
            print(msg, '\r', end="")
            time.sleep(1)
    
            # below two lines is to replace the printed line with white spaces
            # this is required for the case when the number of digits in timer reduces by 1 i.e. from
            # 10 secs to 9 secs, if we dont do this there will be extra prints at the end of the printed line
            # as the number of chars in the newly printed line is less than the previous
            remove_msg = ' ' * len(msg)
            print( remove_msg, '\r', end="")        
    
            # decrement timer by 1 second
            start -= 1
        print("Happy New Year!!")
        return
    
    
    
    if __name__ == '__main__':
        countdown(10)
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-27
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多