简体   繁体   中英

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.

With the try/except, nothing prints on the screen. When i do the Ctrl-C, then all the statements print together (one after the other) and the input statement appears fine.

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 ?

If it is, what other solutions could I use ?

Best !

By default Python will use buffered output. Since sys.stdout is a text stream, debuffering usually takes place when a newline is emitted, but your code isn't emitting any.

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.

@holdenweb has explained it. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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