[Tutor] Sys.argv read parameters
Dave Angel
davea at davea.name
Wed Apr 17 22:18:24 CEST 2013
On 04/17/2013 03:27 PM, Danilo Chilene wrote:
> Dear Python Tutor,
>
> I have the code below(file.py):
>
> import sys
>
> a = 'This is A'
> b = 'This is B'
> c = 'This is C'
>
> for i in sys.argv[1]:
> if sys.argv[1] == 'a':
> print a
> if sys.argv[1] == 'b':
> print b
> if sys.argv[1] == 'c':
> print c
Since this is a loop, I'll assume that argv[1] was supposed to permit
multiple characters. If so, your loop is buggy. And if not, then you
don't want a loop.
>
> I run python file.py a and returns the var a, so far so good.
What do you want to happen if you say
python file.py ac
>
> The problem is that i have a bunch of vars(like a to z), how I can handle
> this in a pythonic way?
>
Use a dictionary (dict). Instead of separate 'variables' use one dict.
(With version 2.7)
import sys
mystrings = { "a" : "This is A",
"b" : "This is B",
"c" : "This is C",
"d" : "This is some special case D",
}
for parm in sys.argv[1]:
if parm in mystrings:
print mystrings[parm]
else:
print "Invalid parm"
If this isn't what you wanted, then you'll have to make it clearer.
1) tell us what version of python
2) supply us with a non-buggy program,
3) be much more specific about what change you want. You don't want
more vars, you presumably want a way to avoid having more vars. Danny
assumed you wanted those exact strings, for a, b, and c, while i assumed
that those were just simple examples.
--
DaveA
More information about the Tutor
mailing list