I would like to create a python script and parse a list of command-line arguments.
Specifically, I would like to give it the following arguments and have it read them as an array. Something like this:
JavaScript
x
3
1
run script.py (['file1.ascii', float_12, float_13, float_14, float_15, float_16],
2
['file2.ascii', float_22, float_23, float_24, float_25, float_26] )
3
where the input array is:
JavaScript
1
3
1
input_array = (['file1.ascii', float_12, float_13, float_14, float_15, float_16],
2
['file2.ascii', float_22, float_23, float_24, float_25, float_26] )
3
and inside the script, I want to do a “for loop” and and assign the variables in this way:
JavaScript
1
9
1
for i in range(0, len(input_array) ):
2
variable_1 = 'filei.ascii'
3
variable_2 = float_i2
4
variable_3 = float_i3
5
variable_4 = float_i4
6
variable_5 = float_i5
7
variable_6 = float_i6
8
#do my calculations
9
Advertisement
Answer
You can convert the array to JSON.
In the calling script, do:
JavaScript
1
8
1
import json, subprocess
2
3
args = json.dumps(
4
['file1.ascii', float_12, float_13, float_14, float_15, float_16],
5
['file2.ascii', float_22, float_23, float_24, float_25, float_26]
6
)
7
subprocess.run(['python', 'script.py', args])
8
and in script.py
you parse the JSON
JavaScript
1
6
1
import json, sys
2
3
input_array = json.loads(sys.argv[1])
4
for filename, var1, var2, var3, var4, var5 in input_array:
5
# do stuff
6