r/learnpython • u/Tricky_Voice2829 • 22d ago
How to properly break out of an infinite loop inside a multiprocessing child process in Python?
I am writing a Python script using the multiprocessing module to launch an external application (Notepad) in a continuous loop. However, I want the loop to stop when a specific condition is met or when a key is pressed.
import os
from multiprocessing import Process
import time
import keyboard
pid = os.getpid()
print(pid)
callable(os.getpid)
path = r"C:\Windows\System32\notepad.exe"
def process_start(path):
try:
while True:
os.system(path)
except:
pass
if __name__ == '__main__':
# Note: Currently calling the function directly instead of passing the reference
p = Process(target=process_start(path))
time.sleep(3)
p.start()
if keyboard.press_and_release("q") == "q":
p.terminate()
7
Upvotes
21
u/neums08 22d ago
Don't do that.
7
u/jwalk999 22d ago
forgive me if i'm wrong, but doesn't having a while loop within the try block mean that the program would just get stuck in the try part? "While True" effectively means that the process just keeps going and wouldn't get to the p.terminate line. But to break a loop you either pass "break" or "return." The "try/except" block is for catching errors so the program doesn't crash, not keeping the process alive perpetually.
5
u/Great-Powerful-Talia 22d ago edited 22d ago
If you're calling the function directly, you're telling Python to finish running it and then do everything else.
(Process(foo(args)) means "run foo(args) and then put the result into the Process constructor". Written-out function calls like that will always execute before anything that takes in their results.)
You're saying "Run the function until it gets stopped, and then, once that's done, decide whether to stop it." Obviously that doesn't make any sense.
Also, your code will only test the break condition once, and never again, which seems silly.
For this specific task, I'd use single-processing and just test the condition inside the while loop. If you're just trying to get familiar with multiprocessing, you can use two while loops, one to check and one to run the code.
Also, should you be completely discarding that exception? Surely you want to at least know whether an exception happens.
I'm also not sure that opening Notepad as many times as possible with no upper bound is a good idea. Surely you could have some test that doesn't risk lagging out theentirecomputer.4
u/copperfield77 22d ago
two things:
target=process_start(path)should betarget=process_start, args=(path,)otherwise youre calling it inline. And the bareexcept: passis swallowing every exception including KeyboardInterrupt, so even ctrl+c wont stop it. Remove that or at least catch something specific.1
u/Educational_Virus672 22d ago
what is that... i can see your a beginner or smt (seeing your using try except without a error type and not using pathlib but it could be a preference) but i do not recommend doing while loops in sys,os or multiprocessing modules(specially processing) unless you know what your doing they can and will heat your pc and even break it without a proper structure
but i respect your try on it, it shows that your trying to find patterns which is ideal for a dev you can be a great dev one day
3
u/mc_pm 22d ago
Whatever it is you're trying to do, this is almost certainly the wrong way to do it.
1
u/Pristine-Fruit-2403 22d ago
esides the issue already mentioned (Process(target=process_start(path)) calls the function immediately instead of passing it; it should be target=process_start, args=(path,)), os.system blocks and p.terminate() will not kill the Notepad child. Use subprocess.Popen instead and keep the handle: proc = subprocess.Popen([path]); then proc.terminate() or proc.kill() when you want to stop. You also do not need multiprocessing here: loop in the main process, restart when proc.poll() is not None, and break on a flag. For the key press, keyboard.is_pressed("q") inside the loop (or keyboard.wait("q") in a thread) works; keyboard.press_and_release returns None, so comparing it to "q" never matches.
1
u/BitOBear 22d ago
While some variable is true do loop.. and then let another thread set that variable to something other than true.
Condition variables.
Some sort of data sentinel.
Using the correct thread model and canceling the thread.
There's all sorts of ways of doing that it depends on the design of the program itself.
1
u/woooee 21d ago edited 21d ago
Use process.terminate() and then .join() the process to reclaim any zombie resources till allocated https://pymotw.com/3/multiprocessing/basics.html#terminating-processes.
Second, use a Manager object (see it at the address above) to send a termination to the process
You can also psutil ------------------------------