How to Make One Python File Run Another

How can I make one python file run another?

There are more than a few ways. I'll list them in order of inverted preference (i.e., best first, worst last):

  1. Treat it like a module: import file. This is good because it's secure, fast, and maintainable. Code gets reused as it's supposed to be done. Most Python libraries run using multiple methods stretched over lots of files. Highly recommended. Note that if your file is called file.py, your import should not include the .py extension at the end.
  2. The infamous (and unsafe) exec command: Insecure, hacky, usually the wrong answer. Avoid where possible.

    • execfile('file.py') in Python 2
    • exec(open('file.py').read()) in Python 3
  3. Spawn a shell process: os.system('python file.py'). Use when desperate.

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()

Run a Python script from another Python script, passing in arguments

Try using os.system:

os.system("script2.py 1")

execfile is different because it is designed to run a sequence of Python statements in the current execution context. That's why sys.argv didn't change for you.

Run another Python script in different folder

There are more than a few ways. I'll list them in order of inverted
preference (i.e., best first, worst last):

  1. Treat it like a module: import file. This is good because it's secure, fast, and maintainable. Code gets reused as it's supposed
    to be done. Most Python libraries run using multiple methods stretched
    over lots of files. Highly recommended. Note that if your file is
    called file.py, your import should not include the .py
    extension at the end.
  2. The infamous (and unsafe) exec command: execfile('file.py'). Insecure, hacky, usually the wrong answer.
    Avoid where possible.
  3. Spawn a shell process: os.system('python file.py'). Use when desperate.

Source: How can I make one python file run another?



Solution

Python only searches the current directory for the file(s) to import. However, you can work around this by adding the following code snippet to calculation_control.py...

import sys
sys.path.insert(0, 'calculation_folder') # Note: if this relavtive path doesn't work or produces errors try replacing it with an absolute path
import calculation

How to run two python scripts one after another in third python script

Check the return code of the subprocess1 and if it is okay, execute the second subprocess.

How to get exit code when using Python subprocess communicate method?



Related Topics



Leave a reply



Submit