0

How to to read tuple dynamically named in command line argument (sys.argv) ?

Below example doesn’t work.

#!/usr/bin/env python
import sys
cmd1 = sys.argv[1]
tpl1 = ('one', 'two', 'three')
tpl2 = ('four', 'five', 'six')
print (cmd1)
val1 = cmd1[0]
val2 = cmd1[1]
val3 = cmd1[2]
print (val1)
print (val2)
print (val3)

current output for script.py tpl1 :

t
p
l

desired output for script.py tpl1 :

one
two
three

Please advise, thanks

1 Answers1

3

Use a dictionary, accessing variables using strings is almost never a good idea.

d = {
      'tpl1': ('one', 'two', 'three'),
      'tpl2': ('four', 'five', 'six')
    }

cmd1 = sys.argv[1]
print (d[cmd1])
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • If I use this how would I assign values from tuple to particular variables? i.e. command line argument = name of the tuple, but val1 = first value from tuple... val2 = second value from tuple etc – user3281086 Feb 06 '14 at 22:26
  • Answer: val1 = (d[cmd1])[0] – user3281086 Feb 06 '14 at 22:39
  • @user3281086 Looking for a generalized answer to this problem will probably lead you to `exec` or `eval`. [Take a look at this explanation of what they do and why it's dangerous to treat user input like code](http://stackoverflow.com/questions/1832940/is-using-eval-in-python-a-bad-practice) just preemptively – colinro Jun 19 '14 at 09:06