Skip to content
Advertisement

Command line array argument into a python script

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:

run script.py (['file1.ascii', float_12, float_13, float_14, float_15, float_16], 
               ['file2.ascii', float_22, float_23, float_24, float_25, float_26] )

where the input array is:

input_array = (['file1.ascii', float_12, float_13, float_14, float_15, float_16], 
               ['file2.ascii', float_22, float_23, float_24, float_25, float_26] )

and inside the script, I want to do a “for loop” and and assign the variables in this way:

for i in range(0, len(input_array) ): 
 variable_1 = 'filei.ascii'
 variable_2 = float_i2
 variable_3 = float_i3
 variable_4 = float_i4
 variable_5 = float_i5
 variable_6 = float_i6
 #do my calculations

Advertisement

Answer

You can convert the array to JSON.

In the calling script, do:

import json, subprocess

args = json.dumps(
    ['file1.ascii', float_12, float_13, float_14, float_15, float_16],
    ['file2.ascii', float_22, float_23, float_24, float_25, float_26] 
)
subprocess.run(['python', 'script.py', args])

and in script.py you parse the JSON

import json, sys

input_array = json.loads(sys.argv[1])
for filename, var1, var2, var3, var4, var5 in input_array:
    # do stuff
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement