0

I need to execute two python script script1.py (path: dir1) and script2.py(path:dir2) in loop.In order to run this two script I need to give the python path. Earlier I used to manually set path and execute the script. Since I need to execute script in loop, How can i create a batch file that could execute one script and after its work is done execute another. I am newbie with batch script. Thanks

HaWa
  • 231
  • 2
  • 4
  • 10

2 Answers2

0

You can create a shell script (which runs for 10 times) for this:

#!/bin/bash
for i in `seq 0 10` ;
do
   echo "Running Script 1"
   python Script1.py <path as argument>;
   echo "script 1 completed"
   echo "Running Script 2"
   python Script2.py <path as argument>;
   echo "script 2 completed"
done

Please clarify if your need is something else.

martineau
  • 119,623
  • 25
  • 170
  • 301
RahulAN
  • 97
  • 1
  • 1
  • 7
0

You can use a python script that calle the subprocess.call() method. It takes a list of strings containing the commands to be called.
You then use that with a try loop to check if the first script executes without errors, and, if so, call the next (optionally with a try as well).

#batch.py
import subprocess
    try:
        subprocess.call(['python3','path/to/script1.py'])
    except Exception as e:
        print('Error: ', e) #alternatively add your logger here
        sys.exit(1)

    try:
        subprocess.call(['python3','path/to/script2.py'])
    except Exception as e:
        print('Error: ', e) #alternatively add your logger here
        sys.exit(1)

you would then execute this using python3 path/to/batch.py from the CLI.

Take note that, if you're using python 2.7 (which you shouldnt unless absolutely necessary), you have to alter the code to call python instead of python3.

For more references and information on the subprocess module check out the python documentation and this answer

Community
  • 1
  • 1
deepbrook
  • 2,523
  • 4
  • 28
  • 49