I am trying to use subprocess
to execute a python script from within a python script but I am having certain issues. Here is what I want to do:
I want to start a main process first (execute python script 1) and after some time into the execution of this process I want to start a subprocess (execute python script 2). Now while this sub process is in execution I wan that the execution of main process also continues and when main process finishes it should wait for the sub process to finish.
Below is the code which I wrote. Here Script1.py
is main process script which I import into my code. Script2.py
is the sub process script which is called using subprocess.Popen()
.
Script1.py
import time
def func():
print "Start time : %s" % time.ctime()
time.sleep( 2 )
print "End time: %s" % time.ctime()
return 'main process'
Script2.py
import time
def sub():
count=0
while count < 5:
print "Start time : %s" % time.ctime()
time.sleep(3)
print "End time: %s" % time.ctime()
x+=1
return 'sub process'
if __name__ == '__main__':
print 'calling function inside sub process'
subval = sub()
Main_File.py is the script which initiated the first process by importing Script1.py
and then starting the sub process also later on
Main_file.py
import subprocess
import sys
import Script1
def func1():
count=0
while x < 5:
code = Script1.func()
if x == 2:
print 'calling subprocess'
sub_result = subprocess.Popen([sys.executable,"./Script2.py"]) # Start the execution of sub process. Main process should keep on executing simultaneously
x+=1
print 'Main process done'
sub_result.wait() # even though main process is done it should wait for sub process to get over
code = sub_result # Get the value of return statement from Sub process
return code
if __name__ == '__main__':
print 'starting main process'
return_stat = func1()
print return_stat
When I run Main_file.py
then the output it executes is not correct. It seems it does not execute the subprocess as I do not see any of print statement written in Script2.py and it stops after main process is done. Also I am not sure about the way of getting the value of the return statement from the sub process. Can anyone help me in trying achieve the correct output.
NOTE: I am new to python and subprocess and so I tried on my behalf first. Please forgive if there is lack of any understanding of concepts