Liam
Liam

Reputation: 429

Calling script with tuples as arguments

I want to be able to call a python script from the command line like this:

python ./pyProg (1, 2) (2, 3)

and then be able to manipulate these (Enter as many as you want e.g. could enter in 10 tuples) within my program?

So far the only way I am able to do something similar is to call it like:

python ./pyProg 1,4 2,2

or:

python ./pyProg "(1, 2)" "(2,2)"

and they come through as strings.. What is the best way to achieve what I am wanting to do?

Thanks

Upvotes: 0

Views: 1424

Answers (2)

RoadRunner
RoadRunner

Reputation: 26315

You could pass the tuples as strings and convert them to actual tuples using ast.literal_eval():

from sys import argv
from ast import literal_eval

for x in argv[1:]:
    tup = literal_eval(x)
    print(tup, type(tup))  

Which can be called like this:

$ python ./pyProg.py "(1, 2)"
(1, 2) <class 'tuple'>

Handling errors:

If the string passed is not a valid expression, both SyntaxError and ValueError could be raised. Therefore, its probably safe to wrap the above in a try/except:

from sys import argv
from ast import literal_eval

for x in argv[1:]:
    try:
        tup = literal_eval(x)
        print(tup, type(tup))
    except (SyntaxError, ValueError):
        print("%s -> Invalid tuple format given" % x)

Which can be seen here:

$ python ./pyProg.py "(1, 2"
(1, 2 -> Invalid tuple format given
$ python ./pyProg.py "(1, 2) (1, 2)"
(1, 2) (1, 2) -> Invalid tuple format given

Upvotes: 2

tripleee
tripleee

Reputation: 189377

If you expect your arguments in a particular format, usability will probably be better if you use a regular argument handling parser which parses the individual values.

arg_tuples = [tuple(t.split(',') for t in sys.argv[1:]]

Omitting the parentheses allows you to omit the quotes on the shell command line (though quoting might of course be necessary for other reasons if your tuple members are not always just numbers).

sys.argv[] is a list of strings by definition, the shell does not (portably) have any other data type.

Upvotes: 1

Related Questions