Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run the sequence of python scripts one after another in a loop?

Tags:

python

bash

cron

How to run sequentially 20 - 30 scripts one-by-one and after the last one is executed - run the first one again and run this iteration on a hourly basis?

I tried to implement it by using crontab, but it's a bulky way. I want to guarantee that only one script for every moment is running. The time of execution for each script is about 1 minute.

I wrote a bash script for such a goal and think to run it every hour by using cron:

if ps ax | grep $0 | grep -v $$ | grep bash | grep -v grep
then
    echo "The script is already running."
    exit 1
else
    python script1.py
    python script2.py
    python script3.py
    ...
    python script30.py
fi

but is it a good way?

like image 469
Павел Иванов Avatar asked Mar 03 '26 19:03

Павел Иванов


2 Answers

From this question, I assume you only want to run the next program when the older one has finished.

I suggest subprocess.call, it will only return to the call of the function when the program that is called has finished executing.

Here's an example. It will run script1, and then script2, when script1 has finished.

import subprocess

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

for program in program_list:
    subprocess.call(['python', 'program'])
    print("Finished:" + program)
like image 86
twaxter Avatar answered Mar 06 '26 08:03

twaxter


Correction to @twaxter's:

import subprocess

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

for program in program_list:
    subprocess.call(['python', program])
    print("Finished:" + program)
like image 45
Rumbles Avatar answered Mar 06 '26 09:03

Rumbles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!