Trigger a python script from a python script

Sachinjose
2 min readMay 26, 2024

In this blog, we will go through multiple approaches to trigger a Python script from another Python script.
Let’s discuss the three different ways to achieve this

  1. import Statement.
  2. exec method.
  3. subprocess module.

Import statement

We can make use of the import statement to call the script from another Python script.

In script2.py, we can import script1.py and call the methods of the script1 to access them.

One disadvantage we have on this approach over the other approaches is that we have to call the methods explicitly to run them.

Using exec method

The exec() function executes the python file in the interpreter directly.

But in Python 2, instead of exec() function, the execfile() function should be used.

exec(open("script_name.py").read())

Using subprocess module

Although all three approaches work just fine, this approach holds an advantage over other methods as subprocess module is capable of running a new script directly and can also return their outputs and error code from the script.

This is a new module that replaced several older modules like os.system, which is used for the similar purpose.

import subprocess

subprocess.call("ScriptName.py", shell=True)

If you wish to open a separate terminal to run the python script, then use the below command.

subprocess.Popen(["python.exe", "script.py"], creationflags=subprocess.CREATE_NEW_CONSOLE)

The advantage of running in a separate terminal is that the triggered python script will keep on running independently even after the closure of the main python script.

Difference between Popen and Call method in subprocess.

Popen :

Popen doesn't block, allowing you to continue with other things in your Python program. Popen returns a Popen object.

Popen('script.py')
print('success') # immediately executed

Call :

call does block, making your script waits for the program to complete. It supports all the same arguments as the Popen constructor. call returns process exit code.

call('script.py')
print('hello') # only executed when notepad is closed

I hope you’ve found this post informative.

Have I missed anything? Do not hesitate to leave a note, comment or message me directly!

--

--