1

I'm a beginner and working on a very basic skill set.

I'm making a simple text game in command line for windows, and have a function that lets users read the most recent statement, and skip it by causing a KeyboardInterrupt like with Ctrl-C.

from time import sleep
def wait(seconds):
    try:
        sleep(seconds)
    except KeyboardInterrupt:
        pass
    return

the issue arises when I want to print something and not have a newline afterwards. In that case, the wait() function will execute before the print() function

# functions properly, but has unwanted newline
print("test", end='test\n')
wait(3)
# in windows CMD, wait() executes before print()
print("test", end='test')
wait(3)

I know there are ways around this like using TKinter, but I want to know why this happens, not how to avoid it entirely.

EDIT: I kept searching and found the issue wasn't the try except block, but sleep(): Error with Print and Sleep in Python copy of the answer:

You should use:

print (a, end="", flush=True)

Because console output is line-buffered.

  • I can't replicate this with your example. With both ways, `\n` and no `\n` it executes in the expected order, print then wait, for me. – stoksc Nov 19 '18 at 03:21
  • I was reading and was about to answer, then saw that you'd already found the answer :). Since you figured it out, you should post an answer to your question; [it's very much allowed](https://stackoverflow.com/help/self-answer)! Welcome to Stack Overflow! – Cyphase Nov 19 '18 at 06:25

1 Answers1

0

I agree with your answer. You should use:

print(a, end="", flush=True)

because console output is line-buffered.

J_H
  • 17,926
  • 4
  • 24
  • 44