Smruti Sahoo
Smruti Sahoo

Reputation: 169

I want to pass multiple arguments to python script from bash script

I have a python script that takes some inputs as arguments. I bash script I want to provide those inputs. here is the input syntax :

usage: $0 <virtualenv-dir>
          <cairo-dir>
          <file-path>
          [--server <es-server>]
          [--port <es-port>]
          [--fields <columns to be uploaded. Comma separated list of columns]
          [--filter <ES filter to use>]
          [--from-time <start time>]
          [--to-time <end time>]
          [--timestamp-field <name-of-timestamp-column>]
          <index-name> 
          <recipients-separated-by-comma>
          <output-file-name>

I want to learn how to assign these inputs to variable in a bash script and pass the variables to python script.

I tried these :

VIRTUAL_ENV=$1
CAIRO=$2
PYTHON_FILE_SCRIPT=$3
INDEX=$4
MAIL_LIST=$5
FILE_OUTPUT=$6
shift
shift

# Activate virtual environment
source $VIRTUAL_ENV/bin/activate

# Set PYTHONPATH
export PYTHONPATH=$UBUNTU

cd $UBUNTU

# a cronjob to collect the data from the device
python $3 $4 $5 $6

Upvotes: 1

Views: 1525

Answers (1)

Anis Ladram
Anis Ladram

Reputation: 163

The python command seems incorrect: you already called shift, so $3, which is the python script, is now $1.

Replace the last line with

python "$PYTHON_FILE_SCRIPT" "$INDEX" "$MAIL_LIST" "$FILE_OUTPUT"

and you should be just fine.

If you want to perform options parsing, I would suggest you use a while loop and shift arguments while parsing. You can use a case to match options easily. Example:

VIRTUAL_ENV="$1"
CAIRO="$2"
PYTHON_FILE_SCRIPT="$3"

while true; do
    case "$1" in
    --server)
        SERVER="$2"
        shift 2
        ;;
    --port)
        PORT="$2"
        shift 2
        ;;
# add other cases
    *)
        break
        ;;
    esac
dome

INDEX=$4
MAIL_LIST=$5
FILE_OUTPUT=$6

# then do what you need to do

Upvotes: 1

Related Questions