Matt
Matt

Reputation: 27

multiprocessing in a dead loop

I want a function to run in parallel to other processes in the background such that when I click ctrl+a, letter is set to a. However, I tried using multiprocessing which doesn't move on from the function, and also it produces a dead loop when I click ctrl+b a single time.

from multiprocessing import Process
import keyboard as kb
def AOrB():
    while True:
        if kb.is_pressed("ctrl+a"):
            letter = "a"
            print(letter)
        if kb.is_pressed("ctrl+b"):
            letter = "b"
            print(letter)

def main():
# Other codes
    p = Process(target=AOrB())
    p.start()
    p.join()

    # Other codes

if __name__ == '__main__':
    main()

Clicking ctrl+b once now produces :

b
b
b
b
b
b
b
b

Upvotes: 0

Views: 49

Answers (1)

user11718531
user11718531

Reputation:

The problem is that you call the function when you assign it as the target in Process. This causes your program to hang at Process(target=AOrB())

Try this instead:

p = Process(target=AOrB)

EDIT:

Here is the full code, to output the key only once:

from multiprocessing import Process
import keyboard as kb
letter = ""
def AOrB():
    global letter
    while True:
        if kb.is_pressed("ctrl+a"):
            if letter != "a":
                letter = "a"
                print(letter)
        if kb.is_pressed("ctrl+b"):
            if letter != "b":
                letter = "b"
                print(letter)

def main():
# Other codes
    p = Process(target=AOrB)
    p.start()
    p.join()

    # Other codes

if __name__ == '__main__':
    main()

Upvotes: 1

Related Questions