Carlos Carvalho
Carlos Carvalho

Reputation: 107

convert external arguments into list

I need to run a script with external arguments where first argument should be a int the second an list : example :

python run_eval_ML.py 5 "(2,4,6,8)"

When I run the script I get :

(base) MyPC:ML$ python run_eval_ML.py 5 "(2,4,5,8)" 
run_eval_ML.py 
5 
(2,4,5,8) 
param_grid {'n_neighbors': '(2,4,5,8)'}

# First ARGV: 5 : OK

But The second argument should be this type : (2,4,5,8) and not '(2,4,5,8)'

When I assign

var2=sys.argv[2] 

and I re assign

param_grid = {'n_neighbors':var2} 

I get

param_grid {'n_neighbors': '(2,4,5,8)'}

and not

param_grid {'n_neighbors': (2,4,5,8)}

Thank you in advance if you can help

Rgds Carlos

Upvotes: 0

Views: 77

Answers (1)

furas
furas

Reputation: 142641

System sends all as strings so you have to split it to list and convert every element to integer

Run without ()

python run_eval_ML.py 5 "2,4,5,8"

and then

# split to list of strings
var2 = sys.argv[2].split(",")

# convert to list of integers
var2 = [int(x) for x in var2]

or in one line

var2 = [int(x) for x in sys.argv[2].splti(",")]

or using map()

var2 = list(map(int, sys.argv[2].splti(",")))

You have also convert first argument from string to integer

var1 = int(sys.argv[1])  

Upvotes: 1

Related Questions