tfpf
tfpf

Reputation: 682

run Python script in Bash loop

I have a python script, which can only be executed a finite number of times before it throws an error (on the terminal). I need to execute it those many times.

Is it possible to do this using a loop in a Bash script? I know a Bash script can read the output of a command from the terminal, but I have no idea how to go about this.

I tried searching for this problem on this site, but I found nothing. Sorry if this has been asked before.

EDIT

I can modify the Python script to return a value depending whether the execution is successful or not. What I want to know is, how to read this returned value in a loop in a Bash script. If the execution was successful, it must execute the Python script again. If not, it must exit.

If there is any other way, that is welcome, too.

Upvotes: 3

Views: 17368

Answers (2)

ivanivan
ivanivan

Reputation: 2215

Right on the command line

user@darkstar:~$ for i in `seq 1 100`; do ./run_the_python; done

Replace 100 with your max value, ./run_the_python with whatever is appropriate to launch your python script.

Update 20190625 /bin/sh: syntax error: unexpected ";"

Upvotes: 4

aze2201
aze2201

Reputation: 559

you can put below code in some executable file. Just replace your start script command into

"#Type start command here"

part. Script will check peer 300 second and will start if process not running. Of course you can optimize if you provide more clear information.

then call script by:

nohup ./executable.sh > Log.log &

#

#!/bin/bash


checkProcess() {
    process=$1
    if [ ${#process} != 0 ]; then
        while true ; do
             processID=$(ps -ef | grep -v grep| grep  "$process"| wc -l)
             if [ ${#processID} == 1 ]; then
                  echo "$(date) : Process is running "
             elif [ ${#processID} -gt 1 ]; then
                  echo "$(date) : Seems more than process running "
             else
                  echo "$(date) : Process is not running"
                  #Type start command here
             fi
             sleep 300s
         done
    else
        echo "You did not passed argument. Please provide process information for GREP"
    fi
} 

checkProcess scriptName

Upvotes: 0

Related Questions