I have a pythons script that needs to run another script.
Flow from python_script_1.py:
run python_script_2.py
pause till python_script_2.py is done
continue python_script_1.py flow
Thanks
I have a pythons script that needs to run another script.
Flow from python_script_1.py:
run python_script_2.py
pause till python_script_2.py is done
continue python_script_1.py flow
Thanks
Normally what you want to do is something similar to this:
def func():
print 'running python_script_2.func()'
import python_script_2
if __name__ == '__main__':
print 'before'
python_script_2.func()
print 'after'
Output
before
running python_script_2.func()
after
What you want to do is to execute some code of the second Python script inside your main module. If you don't have any multithreading management in your code (so 'sequential execution'), you can just do:
from script2 import my_process
if __name__ == '__main__':
print("Be prepared to call stuff from script2")
my_process()
print("Ok, now script2 has finished, we are back in script1")
def my_process():
# do Stuff
You can try subprocess.Popen.
For example:
You have script_1.py
and script_2.py
and you want to run the last from the first, so you can:
# script_1.py
import subprocess
p = subprocess.Popen(
['python', 'script_2.py'], # The command line.
stderr = subprocess.PIPE, # The error output pipe.
stdout = subprocess.PIPE, # The standar output pipe.
)
output, error = p.communicate() # This will block the execution(interpretation) of script_1 till
# script_2 ends.
of course that is the solution if for some reason you can't import the code from script_2.py
as the others answers shows.