0

What I'm trying to achieve: I want that my main process spawn another independent python process. Like:

for i in range(2):
    p = proces()
    p.start()

sys.exit(0)

And my spawned processes should run in the background doing some task :) Because at the moment, if I spawn a process using multiprocessing library and then close my main scripts these processes also exits.

Frederico Martins
  • 1,081
  • 1
  • 12
  • 25
Marcin Kozubi
  • 96
  • 1
  • 7

1 Answers1

0
import time

import multiprocessing

import sys


def run_forever():
    print "ENTERED SUBPROCESS"
    while True:
        print "HELLO from subprocess"
        time.sleep(2)
    print "GOODBYE SUBPROCESS"


if __name__ == "__main__":
    print "STARTING IN MAIN"
    multiprocessing.Process(target=run_forever).start()
    time.sleep(1)
    print "LEAVING MAIN PROG"
    sys.exit()

results in the following output

STARTING IN MAIN
ENTERED SUBPROCESS
HELLO
LEAVING MAIN PROG
HELLO
HELLO
HELLO
HELLO
HELLO
...

of coarse you may have a new problem now (ie you dont actually want run_forever to run forever ... there is no way to exit this process now ...)

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
  • Yes but if I close console etc, my processes are also closed (there is no python in taskmanager) – Marcin Kozubi Sep 02 '16 at 16:23
  • if you close the shell then yes, the process is halted ... that is different than what you asked... the trick is to trigger it differently (ie schedule it using cron or windows scheduler) or perhaps run it as a "windows service" using something like http://stackoverflow.com/questions/32404/is-it-possible-to-run-a-python-script-as-a-service-in-windows-if-possible-how ... but the bottom line is the OS will close any subprocess associated with a given shell when the shell is closed (this is OS and not python specific) – Joran Beasley Sep 02 '16 at 16:27