Search code examples
pythonprintingoutputnewlinepyttsx3

pyttsx3 delays print statement on the previous line


I've noticed a weird bug when using pyttsx3.speak() after a print statement that has the end='' argument set. Take a look at my code.

I've done a bit of research, and I couldn't find anything that's related to this issue. And I couldn't find a reason why exactly this is happening. The first thing that came to my mind is that maybe the default print() function behavior won't print the statement, unless there's a new line. Like the standard output isn't printed to unless there's a new line.

import pyttsx3

print("This should be before speaking, ", end='')
pyttsx3.speak("Hi")
print("and this should be after speaking")

The normal logic would be that it would print the first statement, speak hi, then print the second statement. However, it doesn't print anything until pyttsx3.speak() finishes. This only happens if I specify end='' in the print statement. If I remove it, the logic is completely fine.


Solution

  • Issue isn't with pyttsx3, but it's a feature in print()

    Ok, so it appears that the same issue happens even with using time.sleep() function, which means that pyttsx3 isn't the issue. I looked in the documentation of print() function here, and specified flush=True with the first statement, and it worked completely fine.

    From my understanding, when you don't have a newline in your print statement, the output would still be in the buffer till there's a new line. So technically, the print statement is executed, but the output is still in the buffer and not visible to you. When you do flush=True, you force the output to go the stdout instead of staying in the buffer. I don't know why this isn't mentioned particularly in Python documentation.

    Thanks for reading this. Would it be normal to create an issue on Github on the official Python repository for that? To recommend adding this detail to the documentation.

    Edit

    This feature is mentioned in the docs. It says that Changed in version 3.9: Non-interactive stderr is now line-buffered instead of fully buffered, which makes sense now.