run python scripts in sequence

How to Run Python Scripts in Sequence

Python is a powerful programming language that allows you to perform tons of things. Sometimes you may need to run multiple python scripts one after the other, in a sequence. You may also want to run a python script only after the previous one has executed. In this article, we have learnt how to run python scripts in sequence.


How to Run Python Scripts in Sequence

It is quite easy to run python scripts in sequence. Let us say you have scripts script1.py, script2.py and script3.py that you want to run one after the other.

Here is the code to run these scripts sequentially one after the other.

import subprocess

program_list = ['script1.py', 'script2.py', 'script3.py']

for program in program_list:
    subprocess.call(['python', 'program'])
    print("Finished:" + program)

In the above code, we use subprocess.call that returns the control back to the calling functions only after the called program has finished execution.

If the above code doesn’t work on your system, you can try using the following code, where we use program without quotes.

import subprocess

program_list = ['script1.py', 'script2.py', 'script3.py']

for program in program_list:
    subprocess.call(['python', program])
    print("Finished:" + program)

Alternatively, you can also use exec() function to run these scripts one after the other.

program_list = ["script1.py", "script2.py", "script3.py"]

for program in program_list:
    exec(open(program).read())
    print("\nFinished: " + program)

You can also simply create a string with names/paths to the different scripts, run a for loop through it, and call the shell script in each iteration.

scripts = "script1.py script2.py script3.py"
for s in $scripts
do
    python $s
done

In this article, we have seen several ways to run python scripts one after the other in a sequential manner. Typically, system administrators require to run multiple python scripts sequentially to automate certain tasks and processing. They can use this method to run a batch of scripts on their system, without manually executing each one individually. You can also add the above code in another python script and schedule a cronjob to run that python script on a regular basis. This will completely automate even the sequential calling of python scripts.

Also read:

How to Download Attachment from Gmail using Shell Script
How to Do Google Search from Terminal
How to Backup WordPress to Dropbox
How to Download Attachment from Gmail using Python
How to Read File Line by Line Into Python List

Leave a Reply

Your email address will not be published.