Confusing python problem

0 votes
asked Aug 23, 2010 by violet

As part of a large python program I have the following code:

for arg in sys.argv:
    if "name=" in arg:
            name = arg[5:]
            print(name)
    elif "uname=" in arg:
            uname = arg[6:]
            print(uname)
    elif "password=" in arg:
            password = arg[9:]
            print(password)
    elif "bday=" in arg:
            bday = arg[5:]
            print(bday)
    else:
            pass

The program expects something like:

python prog.py "name=Kevin" "uname=kevin" "password=something" "bday=01/01/01"

When I try to use "uname" later, the program fails, claiming "uname is not defined" I added the "print()" lines to try and debug and the "print(uname)" always shows "=kevin" regardless of the index number I put there (here "6:"). The other statements seem to work fine. Is this a bug in python? I am very confused.

Thanks in advance.

2 Answers

0 votes
answered Aug 23, 2010 by mark

The elif "uname=" is never run because the string "name=" is in "uname=". Essentially, you are overwriting your name variable.

>>> "name=" in "uname="
True

You could reorder your ifs so that so that the uname occurs before the name one.

0 votes
answered Aug 23, 2010 by s-lott

Let's look closely at this.

if "name=" in arg:
        name = arg[5:]
        print(name)
elif "uname=" in arg:
        uname = arg[6:]
        print(uname)

When I apply this to "name=Kevin", which rule works? Just the first one, right?

When I apply this to "uname=kevin", which rule works? First one? Second one? Both? Interestingly, the first one works. I see name=kevin inside uname=kevin. Not what you wanted, was it?

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...