3

I have a function in python with arguments.Within the same file I call that function(call it foo). Is there any way in python(for Win7) that I can create different independent processes from the parent process with each process executing foo with different set of arguments(obviously independent from the parent process as well)? Can a console be also attached to these process?

PS: I know that if it is a separate script or exe then we can use Popen.subprocess() module. But here the problem is of assigning a function(code) to different process(independent from each other as well as of the parent).

This is the function.

import subprocess
import os
import string
def add(x,y):
     return x+y

This is the input file:

1 2
3 4
5 6

Now if function were written in some separate file(add.py) we can directly use subprocess.Popen() to call "add.py" for each set of arguments from the input file. But if the function is written in the same file as the main file then how to assign a new process to each set of arguments from the input file shown? I can't use fork() because there isn't any for Windows.

rahuljain1313
  • 141
  • 1
  • 1
  • 8
  • 2
    Possible duplicate of http://stackoverflow.com/questions/23397/whats-the-best-way-to-duplicate-fork-in-windows – Sam Jun 18 '15 at 09:17
  • @Sam But I am reading a file(a loop) and creating a new Process every time for each set of args.Also they should be independent of parent process and should have a separate console. – rahuljain1313 Jun 18 '15 at 09:21
  • Why dont you just run each function call in a thread? - why the need for a seperate process? - if you want a window for each thread, just as a monitor, consider a simple GUI like tKinter and add a text frame whenever you create a new thread.. – Henrik Jun 18 '15 at 09:23
  • @Henrik threads would be dependent on the parent process. I need that function to be in infinite loop. – rahuljain1313 Jun 18 '15 at 09:33

1 Answers1

1

Yes you can. I wouldn't choose this path myself, but it's possible. This is sometimes referred to as a detached process, or a daemon.

better implementations for deamons exists, but the basic idea can be achieved using this:

import subprocess
import sys

print "runMe started"
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)

def runMeAsChild(args):
    if args is None or len(args) == 0:
        args = []
        args.append("stop")
    cmd = "start cmd /k python " + sys.argv[0]+ " " + " ".join(args)
    proc = subprocess.Popen(cmd, shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)

if len(sys.argv) == 1:
    runMeAsChild(["test"])
    runMeAsChild(["once", "again"])

if you want the console to automatically close after execution, use /c instead of /k in the cmd string

Henrik
  • 2,180
  • 16
  • 29