1
from time import sleep

def o1():
    while True:
        print("1 : )")
        sleep(1)

def o2():
    while True:
        print("2 : )")
        sleep(1)

if __name__=="__main__":
    import multiprocessing
    p1 = multiprocessing.Process(target=o1)
    p2 = multiprocessing.Process(target=o2)
    p1.start()
    p2.start()

    def close():
        print("close o1")
        p1.join() #the process does not end as a result

    def start():
        print("start o1")
        try:
            p1.start()
        except AssertionError:
            print("Nothing")

    import keyboard
    keyboard.add_hotkey('q', close)
    keyboard.add_hotkey('e', start) #after q, nothing happens trying to press "e"

I need to close the process and reopen it by hotkey. (I did two processes in the code, as this fully reflects the program in which I need this function)

I'm sorry for my english : )

userpy
  • 17
  • 4

1 Answers1

1

First of all, p1.join() patiently waits for p1 to finish by itself -- which it won't do, since it's running an infinite loop. Use p1.terminate() here.

Secondly, you can't re-start a process that has finished (in fact, that is the AssertionError you are erroneously catching). There are two solutions here:

  1. suspend and resume the process, rather than terminating it
  2. Start an entirely new process in its place

Here is my implementation of the second approach. Due to a multiprocessing quirk I had to split my code across multiple files:

procs.py

from time import sleep

def o1():
    while True:
        print("1 : )")
        sleep(1)

def o2():
    while True:
        print("2 : )")
        sleep(1)

main.py

from procs import *

if __name__ == "__main__":
    import multiprocessing
    p1 = multiprocessing.Process(target=o1)
    p2 = multiprocessing.Process(target=o2)
    p1.start()
    p2.start()

    def close():
        print("close o1")
        p1.terminate()

    def start():
        global p1
        if p1.is_alive():
            return
        print("start o1")
        p1 = multiprocessing.Process(target=o1)
        p1.start()

    import keyboard
    keyboard.add_hotkey('q', close)
    keyboard.add_hotkey('e', start)
xjcl
  • 12,848
  • 6
  • 67
  • 89
  • It clears the console when I start a new process. Can I fix this somehow? And this is how it works, thanks!) – userpy Nov 13 '20 at 19:41
  • Does it clear the console when you start a new process with 'e' or a new main process? It doesn't clear the console _for me_ when I press 'e' (I'm using PyCharm) – xjcl Nov 13 '20 at 19:46
  • I just put it in my code right away, this is probably the problem. I will try to fix it myself. – userpy Nov 13 '20 at 20:03