Explain Codes LogoExplain Codes Logo

How to call a script from another script?

python
functions
modules
best-practices
Nikita BarsukovbyNikita Barsukov·Oct 31, 2024
TLDR

To execute another Python script, use subprocess.run():

import subprocess subprocess.run(["python", "your_script.py"])

This command launches your script (your_script.py) as if you ran it from your terminal.

Calling Python scripts: Nitty-gritty

In Python, executing a script from another script is straightforward. However, there are fundamental practices to keep in mind to avoid confusion.

Import a Python module

Before calling mutual scripts, convert the code into a module for easy access:

# service.py import test1 # Importing the module, test1.py test1.some_function() # Whoooa! We just called a function from test1.py.

Both scripts should be found in the same directory for relative imports.

Check if a script is the main program

Use the if __name__ == '__main__' idiom to make your script both an importable module and a standalone script:

# test1.py def main(): # Drop your script code here pass if __name__ == '__main__': main() # So, are we having fun yet?

Wrapping your code this way lets you control what to execute upon import.

Using the exec function

exec(), a built-in Python function available in Python 3, runs a file within another script. Stay sharp when using exec though! Namespace handling is necessary:

exec(open('test1.py').read()) # Very sly but possibly cunning!

Due to potential security risks, it is advisable to use exec() sparingly.

Manage scripts separation with subprocess

Python's subprocess module lets you control and isolate scripts for execution. Here's how to utilize subprocess.call():

import subprocess subprocess.call(['python', 'test1.py']) # "I'm calling you. Please pick up!"

Don't get lost. Subprocess documentation is a useful resource.

Direct execution using the os module

For simpler tasks or when you need backward compatibility with older Python versions, os.system() is ready to help:

import os os.system('python test1.py') # "Hey, I can be just as useful!"

With os.system(), remember to always add your Python interpreter to your system's path.

Encapsulate logic in a main function

For well organized and modular Python scripts, define a main() function. You can also call it from another script:

# test1.py def main(): print("I am the main function. Sup?") if __name__ == '__main__': main()
# service.py import test1 test1.main() # Sounds like we're playing the main card here!

Avoid script calling pitfalls

A couple of things can bring to a screeching halt your otherwise jubilant script calling...

Keep an eye on namespaces

When calling scripts, always avoid name conflicts. A variable overwrite or a method redefinition could lead to subtle bugs.

Check your working directory

The location of your scripts matters. If your script can't be found, Python cannot run it.

Learn to love imports

Grasp the difference between importing modules and running them directly. This will help you avoid any unintended side effects.