python – What is the best way to call a script from another script?
python – What is the best way to call a script from another script?
The usual way to do this is something like the following.
test1.py
def some_func():
print in test 1, unproductive
if __name__ == __main__:
# test1.py executed as script
# do something
some_func()
service.py
import test1
def service_func():
print service func
if __name__ == __main__:
# service.py executed as script
# do something
service_func()
test1.some_func()
This is possible in Python 2 using
execfile(test2.py)
See the documentation for the handling of namespaces, if important in your case.
In Python 3, this is possible using (thanks to @fantastory)
exec(open(test2.py).read())
However, you should consider using a different approach; your idea (from what I can see) doesnt look very clean.
python – What is the best way to call a script from another script?
Another way:
File test1.py:
print test1.py
File service.py:
import subprocess
subprocess.call(test1.py, shell=True)
The advantage to this method is that you dont have to edit an existing Python script to put all its code into a subroutine.