Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiprocessing beside a main loop

I'm struggling with a issue for some time now. I'm building a little script which uses a main loop. This is a process that needs some attention from the users. The user responds on the steps and than some magic happens with use of some functions

Beside this I want to spawn another process which monitors the computer system for some specific events like pressing specif keys. If these events occur then it will launch the same functions as when the user gives in the right values.

So I need to make two processes: -The main loop (which allows user interaction) -The background "event scanner", which searches for specific events and then reacts on it.

I try this by launching a main loop and a daemon multiprocessing process. The problem is that when I launch the background process it starts, but after that I does not launch the main loop. I simplified everything a little to make it more clear:

import multiprocessing, sys, time

def main_loop():
    while 1:
        input = input('What kind of food do you like?')
        print(input)

def test():
    while 1:
        time.sleep(1)
        print('this should run in the background')

if __name__ == '__main__':
    try:
        print('hello!')
        mProcess = multiprocessing.Process(target=test())
        mProcess.daemon = True
        mProcess.start()
        #after starting main loop does not start while it prints out the test loop fine.
        main_loop() 
    except:
        sys.exit(0)
like image 760
Ecno92 Avatar asked Jun 15 '26 15:06

Ecno92


1 Answers

You should do

mProcess = multiprocessing.Process(target=test)

instead of

mProcess = multiprocessing.Process(target=test())

Your code actually calls test in the parent process, and that call never returns.

like image 187
shx2 Avatar answered Jun 17 '26 04:06

shx2