I have a Python script that I want to run from a bash, and it needs multiple string arrays/lists inputs. This answer by lorenzog in another question explains how to do it with one array, and it works fine. But how can I pass multiple arrays? Here's what I've tried so far:
Bash script:
#!/bin/bash
declare -a first=("one" "two" "three")
declare -a second=("four" "five")
declare -a third=("six")
declare -a fourth=("seven" "eight")
python argsprob.py "${first[@]}" "${second[@]}" "${third[@]}" "${fourth[@]}"
Python script:
#!/usr/bin/env python3
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('first', nargs='+')
parser.add_argument('second', nargs='+')
parser.add_argument('third', nargs='+')
parser.add_argument('fourth', nargs='+')
args = parser.parse_args()
print(args.first)
print(args.second)
print(args.third)
print(args.fourth)
Output
$ bash argsprob.sh
['one', 'two', 'three', 'four', 'five']
['six']
['seven']
['eight']
Desired output
['one','two','three']
['four','five']
['six']
['seven','eight']
As you can probably tell I have no idea what I'm doing. I've tried other ways of using argparse (more arguments, different "nargs", etc) but none of them works. Any help is appreciated!
sys.argv. I think your bash command expands the arrays in to one long list of strings. Soargparsehas no idea of where your originalfirstends andsecondbegins. It allocates one string each for the last 3 arguments (because of their '+'), and allocates the rest to the first.nargsto 3,2,1,2 respectively.optionals). Then the flags ('--first', etc) act as delimiters between the arrays.