0

I would like to ask, is there any option to make function call in another process? For example:

def foo()
    while True:
        do_something...
#main function
def main()
    foo()
    some_other_actions...
    #end

I would like to make foo running in some other process yet allow main() to normal end and allow user to write anything else in terminal, something like:

  • user run in terminal main()
  • main ends (foo function still working)
  • user can run in terminal anything else (without switching terminal window) yet foo function still working in some other process

I know that there are some answers like, using threading or multiprocess but after using them, program will not stop until foo() function end. Is there any option to make such a thing in Python2.7?

Thanks in advance!

Shreyash S Sarnayak
  • 2,309
  • 19
  • 23
Thodgnir
  • 148
  • 1
  • 11
  • Have a look at the multiprocessing module – tuxtimo Jun 11 '17 at 12:25
  • As far as I used multiprocessing module, program will not exit until foo() function end, or there are some options that allow to main process end leaving foo() process alive? – Thodgnir Jun 11 '17 at 12:28
  • voting to close as a duplicate of https://stackoverflow.com/questions/13095878/deliberately-make-an-orphan-process-in-python – Matti Lyra Jun 11 '17 at 12:40
  • Possible duplicate of [Deliberately make an orphan process in python](https://stackoverflow.com/questions/13095878/deliberately-make-an-orphan-process-in-python) – Matti Lyra Jun 11 '17 at 12:40

1 Answers1

0

You can use the multiprocessing module to do this. There are several options for how to actually implement the whole thing, probably the best would be to create a process pool and a job queue. Whenever you get some action that needs to be executed you add it to the job queue from the process running main and one the workers in the pool will pick it up.

The module is pretty well documented so you should find everything you need from the official python docs for multiprocessing.

There's a question on SO on how to launch orphaned processes in python here, but you really want to think twice if you want to do that. Are the subprocess calls guaranteed to end?

You could also do something crazy like use ZeroMQ as a queuing system for the job to be executed but that's probably beyond the scope of what you're looking for here. Might be an interesting read though

Matti Lyra
  • 12,828
  • 8
  • 49
  • 67