run multiple python files

How to Run Multiple Python Files One After the Other

Sometimes you may need to run multiple python files one after the other. There are several ways to do this. In this article, we will learn different ways to run multiple python files present in folder.


How to Run Multiple Python Files One After the Other

Let us say you have the following python files a.py, b.py and c.py.

#file a.py
print("a")

#file b.py
print("b")

#file c.py
print("c")


Now we will look at the different ways to run multiple python files.

1. Using Terminal/Command Prompt

The simplest way to run these files one after the other is to mention them one after the other, after python command.

$ python a.py b.py c.py
a
b
c


2. Using Shell Script

You can also create a shell script test.sh. for this purpose.

$ vi test.sh

Add the following lines to it.

file_list=("/home/ubuntu/a.py" "/home/ubuntu/b.py" "/home/ubuntu/c.py")

for py_file in "${file_list[@]}"
do
    python ${py_file}
done

Save and close the file. Make it an executable with the following command.

$ chmod +x test.sh

In the above code, we maintain the full paths to the 3 files in an array file_list. Then we run a for loop to go through this array and call python command to run each file. We use full paths to ensure that the shell script runs from any location.


3. Using Import

In this case, you can simply import os module into another python file and run them using os.system function.

import os
  
os.system('python /home/ubuntu/a.py')
os.system('python /home/ubuntu/b.py')
os.system('python /home/ubuntu/c.py')

Alternatively, you can also import the 3 files into another python file and run their functions from this file. Let us say your 3 python files a.py, b.py and c.py have functions fa(), fb() and fc() respectively.

#file a.py
def fa()
  print("a")

#file b.py
def fb()
  print("b")

#file c.py
def fc()
  print("c")

You can create a fourth python file d.py in the same folder as other 3 python files, which imports the other 3 python files and runs their functions, as shown below.

import a
import b
import c

result_a = a.fa()
result_b = b.fb()
result_c = c.fc()

In this article, we have learnt how to run multiple python files.

Also read:

How to Merge PDF Files Using Python
How to Do Incremental Backup in MySQL
How to Pass SSH Password in Shell Script
MySQL Change Table Storage from InnoDB to MyISAM
How to Install Fonts in Ubuntu

2 thoughts on “How to Run Multiple Python Files One After the Other

    • Thank you for your feedback. We have updated the shell script in #2 to run a list of python scripts.

Leave a Reply

Your email address will not be published.