简体   繁体   English

我的打印语句在try \\ except循环中不起作用

[英]My print statement doesn't work in a try\except loop

I have done a little function that acts as a timer, updating the line as minutes go (put a second here for test. 我已经完成了一个小功能,可以用作计时器,并在几分钟内更新该行(在此处进行测试。

I wanted to use the KeyboardInterrupt to exit this part of my program so used the try/except method, but something odd happens. 我想使用KeyboardInterrupt退出程序的这一部分,所以使用了try / except方法,但是发生了一些奇怪的事情。

With the try/except, nothing prints on the screen. 使用try / except时,屏幕上不打印任何内容。 When i do the Ctrl-C, then all the statements print together (one after the other) and the input statement appears fine. 当我执行Ctrl-C组合键时,所有语句一起打印(一个接一个),输入语句看起来很好。

Like this : 像这样 :

ou have been working for 0 minutesYou have been working for 1 minutesYou have been working for 2 minutesYou have been working for 3 minutesYou have been working for 4 minutesYou have been working for 5 minutesYou have been working for 6 minutesYou have been working for 7 minutesYou have been working for 8 minutesYou have been working for 9 minutesYou have been working for 10 minutesYou have been working for 11 minutesAre you sure you want to finish your working session ? (y/n)

Here is my code: 这是我的代码:

def timer():
    minutes = 0
    startDateTime = datetime.datetime.now()
    stringDateTime = startDateTime.strftime('%m/%d/%Y, at %H:%M:%S' )
    while True:
        try:
            time.sleep(1)
            print('You have been working for {} minutes'.format(minutes), end='')
            minutes += 1
        except KeyboardInterrupt:
            choice = input('Are you sure you want to finish your working session ? (y/n)')
            if choice == 'y':
                    log_time(stringDateTime, minutes)
            elif choice == 'n':
                    pass
            pass

Is this behavior is inherent to try/except ? 这种行为是try / except固有的吗?

If it is, what other solutions could I use ? 如果是,我还可以使用其他解决方案吗?

Best ! 最好 !

By default Python will use buffered output. 默认情况下,Python将使用缓冲输出。 Since sys.stdout is a text stream, debuffering usually takes place when a newline is emitted, but your code isn't emitting any. 由于sys.stdout是文本流,因此通常在发出换行符时进行缓冲,但是您的代码未发出任何缓冲。

If you left your program to run for a while I suspect you would eventually see a huge splurge of output as the buffer filled up. 如果您让程序运行一段时间,我怀疑您最终会在缓冲区填满时看到大量的输出。

To force debuffering, simply use 要强制去缓冲,只需使用

sys.stdout.flush()

when you want to be sure everything printed so far is emitted. 当您要确定到目前为止已打印的所有内容均已发出时。

As @wjandrea points out in a comment to another answer, adding flush=True to print 's arguments is a simpler solution. 正如@wjandrea在对另一个答案的注释中指出的那样,在print的参数中添加flush=True是更简单的解决方案。

@holdenweb has explained it. @holdenweb已经解释了它。 I am just adding this for better clarity. 我只是为了更好地说明而添加此内容。

If you try to print like this then it will be saved in the buffer and all will be outputted after the loop exits. 如果尝试这样打印,则它将被保存在缓冲区中,并且在退出循环后将全部输出。 which in this case will take 13s for the string of length 13. 在这种情况下,长度为13的字符串将花费13s。

import time 

strn = "StackOverflow"

for i in range(0, len(strn)): 
    print(strn[i], end ="")
    time.sleep(1)

but with the flush, it will output one character after every second. 但是使用同花顺时,它将每秒输出一个字符。

import time 
import sys

strn = "StackOverflow"

for i in range(0, len(strn)): 
    print(strn[i], end ="")
    sys.stdout.flush()
    time.sleep(1)

Since you're not printing a newline at the end of your print statement, it's not getting flushed to output. 由于您不会在打印语句的末尾打印换行符,因此不会刷新输出。 Try calling sys.stdout.flush() after every print. 尝试在每次打印后调用sys.stdout.flush()

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

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