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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With