Home > Net >  Pass arguments(a list) from /bin/sh to python
Pass arguments(a list) from /bin/sh to python

Time:12-02

I am having a test.py file that are below:

year= sys.argv[1]
for i in range(len(year)):
   
    print("Working on year",year[i])

year should take a list of years such as ['2021','2022'] and loop thru it. And I am constructing a .sh file that can just pass a list of years to python.Here is the test.sh file:

#!/bin/bash

year=$1


echo 'Working on' $year 'year'

python path/test.py $year 

I am hoping to have it set up correctly so I can just run this in command line:

sh test.sh '2021 2022'

and it'd print out years. However, it loop thru 2,0,2,1 instead of 2021 and 2022. How do I fix this?

CodePudding user response:

In your shell script, pass the whole argument list through by using "$@" to expand to "$1" "$2" "$3" ...etc, for however many arguments are available:

#!/bin/bash
echo "Requesting work on years:"
printf ' - %s\n' "$@"
python path/test.py "$@"

In your Python script, process that whole argument list:

#!/usr/bin/env python
import sys
for i in sys.argv[1:]:
    print("Working on year", i)
  • Related