2

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

Alex
  • 462
  • 1
  • 7
  • 19
  • Well I want it to continuously print something out, and it will only stop once the user presses the "q" key – Alex May 31 '20 at 23:18
  • Not enough info in original question, detecting a button press will vary depending on your OS. However, in my opinion you are overthinking it by trying to use concurrency. – Teejay Bruno May 31 '20 at 23:29
  • Oh I'm using Linux. And is there a different approach to this? One that doesn't use concurrency? – Alex May 31 '20 at 23:32
  • You can use package `keyboard` and do simple loop `while not keyboard.is_pressed('q'): print("Hello world!")`. – maciek97x May 31 '20 at 23:34

1 Answers1

2

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
Artiom Kozyrev
  • 3,526
  • 2
  • 13
  • 31