1

I would like to pass a list of strings as an argument to a Python script.

I have a bash script bash_script.sh like:

local dtype=float32
declare -a tokens
tokens=("CLS", "HI")
    
python -m python_script.py --langs abc --tokens ${tokens[@]} --dtype $dtype

The python script python_script.py being called is:

def parse_args():
    """Parse CLI arguments"""
    parser = argparse.ArgumentParser(
        description='Do something')
    parser.add_argument('--langs', type=str, required=True)
    parser.add_argument('--tokens', type=list, required=False)
    parser.add_argument('--dtype', type=str, default='float16')

def main(args):
    """Handle CLI args"""
    print(args.padding_tokens)
    ...

if __name__ == '__main__':
    main(parse_args())

However, when I run bash bash_script.sh, I get the error: __main__.py: error: unrecognized arguments: HI

I have also tried to do

declare -a padding_tokens
padding_tokens=("CLS, HI")

and then passing $padding_tokens[@] into the Python script from the Bash script, but still get the same error.

How can I pass the list of strings as an argument to a Python script from a Bash script, and then process the list of strings in the Python script from the args?

Asmita Poddar
  • 524
  • 1
  • 11
  • 27
  • 1
    Hi, tried looking here? https://stackoverflow.com/questions/15753701/how-can-i-pass-a-list-as-a-command-line-argument-with-argparse – Shawn Ramirez Feb 17 '22 at 20:15
  • 4
    Try putting double quotes around the argument to prevent [word splitting](https://mywiki.wooledge.org/WordSplitting), like this: `"${tokens[@]}"`. – codeforester Feb 17 '22 at 20:53

0 Answers0