Search code examples
pythonmultithreadinggetch

How to run a side task while also waiting for getch?


So I have this small program (using Linux):

import getch

while True:
  print("Hello World!")

  key = getch.getch()

  if key == 'q':
    break

So all it does is wait for the user to hit a key, and they displays "Hello World!" to the console. However, is there a way so that I can continuously display "Hello World!" to the console, and the only way to get it to end is if the user presses the "q" key?

This question is similar to this one, but it's in C++.


My first thought was to look up threading, however, I tried all the threads I could find and none of them worked. Then I came across the Global Interpreter Lock (GIL), and it supposedly prevents "multiple native threads from executing Python bytecodes at once."

Then I tried to use multiprocessing, but it still didn't work for me. This is how far I got using it:

import multiprocessing 
import getch

def test1():
  print("Hello World!")

def test2():
  key = getch.getch()

  if key == 'q':
    exit()

while True:
  p1 = multiprocessing.Process(target=test1, args=()) 
  p2 = multiprocessing.Process(target=test2, args=())

  p1.start()
  p2.start() 

  p1.join()
  p2.join()

Am I missing something here? Or is there another way in which I can do something while also waiting for getch()? Or do I have to write this in another language that supports multithreading like C++?

Thanks


Solution

  • I was not able to install fetch, probably because I am on Windows at the moment, but you can implement what you want (However, is there a way so that I can continuously display "Hello World!" to the console, and the only way to get it to end is if the user presses the "q" key?) the following way:

    import time
    from threading import Thread
    
    
    def another_thread():
        while True:
            time.sleep(2)
            print("Working...\n")
    
    
    def main_thread():
        while True:
            x = input("Press a key: \n")
            if x == "q":
                break
    
    
    if __name__ == '__main__':
        # create another Thread object
        # daemon means that it will stop if the Main Thread stops
        th = Thread(target=another_thread, daemon=True)
        th.start()  # start the side Thread
        main_thread()  # start main logic