0

So I was coding a program where it needs to take user input and print something in the same time so I obviously used threading, however I noticed that the print is not working properly and I tried to create a simple POC:

└─# python3
Python 3.11.4 (main, Jun  7 2023, 10:13:09) [GCC 12.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import threading
>>> import time
>>> 
>>> def print_something():
...     while 1:
...             print("This is an important string", end="")
...             time.sleep(1)
... 
>>> 
>>> 
>>> 
>>> thread = threading.Thread(target=print_something)
>>> thread.daemon = True
>>> thread.start()
This is an important string>>> 
This is an important stringThis is an important string>>> 
This is an important string>>> 
>>> 
>>> 
>>> input()
This is an important stringThis is an important stringThis is an important stringThis is an important string''
>>> 
This is an important stringThis is an important string>>> 
>>> 

as you can see (it might not be understandable but let me explain) it is only printing the This is an important string only when I press enter, and it is printing all the 'queue' (let's assume) at once. Why is that and how can I make it print in real-time aka as soon as the 1 second finishes print the string without me having to press enter.

  • I suspect this is because the main thread has the GIL locked while you're in `input()`. – Barmar Sep 01 '23 at 22:43
  • 1
    No, it's nothing to do with threads; a single-threaded program will show the same issue with holding up the printing (except of course that you wouldn't be able to interrupt the `sleep` with an `input`). The problem is with `end=''`. Please see the linked duplicate for details. – Karl Knechtel Sep 01 '23 at 23:41

0 Answers0