Run a Python Script from another Python Script (Using exec function)


As programmers, we are always looking to simplify things and make everything run smoothly as can be. However, when building out a lot of programming scripts it can create a lot of headaches in terms of organization and what runs where and when.

One solution I have found that helps keep things in order is to run scripts from a main script. This helps keep control of a project’s process from start to finish.

In this quick tutorial (using Python3), we are going to run a script and then build another script that will run that first script for us. We will use the .read() and exec functions to accomplish this.

Script 1: Script_1_Print_Text.py

Here we have a very simple script that only will display (print) a line of text (This is the text output of Script 1).

#Run Script 1
print('This is the text output of Script 1')

Output:

This is the text output of Script 1

Script 2: Execute Script 1 from Script 2

Ok, simple enough. Next, we create a second script that will execute that first script and print it’s own text. We use the exec function which is a Python built in function and the .read() function, also a built in function.

#Running the first script
exec(open("Script_1_Print_Text.py".read()))
#Now print text from script 2
print('This is the text output of Script 2')

Output:

This is the text output of Script 1

This is the text output of Script 2

We have now successfully run the first script from another script with each text string from the scripts showing in the outputs.

To run a script from a different folder or directory, we can also just specify the folder location in the code like below.

folder_location = 'C:/Users/Files/Location'
exec(open("{}/Script_1_Print_Text.py".format(folder_location)).read())

or like this with the folder specified in the code:

exec(open("C:/Users/Files/Location/Script_1_Print_Text.py").read())
This simple method for Python3 can be used to run many scripts one after another by just repeating the code with your desired script names and locations.

I have found this to be helpful in organizing a straightforward process for executing coding projects.

Article by Zachary Storella – See more programming posts on our Python Page