简体   繁体   中英

Sys.argv python error list index out of range

I'm new user of stackoverflow, besides I'm not an English guy, so I'm sorry for my english.

I was programming in python 'til I got a mistake tho I'm not able to figure out what's wrong...

#!/usr/bin/env python2.7

from random import choice
import sys

def help():
    print ("Please, you need to introduce a Int in this way: PWrand 10")

def PWrand(insert_by_user):
    chars = 'ABCDEFGHIJKLMNOPQRSTUWXYZabcdefghijklmnopqrstuwxyz0123456789!-_:.,;&)('

    for password in range(insert_by_user):
        sys.stdout.write(choice(chars))

 #Command Line

if __name__ == '__main__':

    if len(sys.argv) < 2 or len(sys.argv) > 2:
        help()

    elif (type(sys.argv[2]) != int):
        print("It need to be an Int!")

    else:
        insert_by_user = (sys.argv[2])
        print(PWrand(insert_by_user))

So, this is what I take.

Traceback (most recent call last):
  File "./passwordrandom.py", line 24, in <module>
    elif (type(sys.argv[2]) != int):
IndexError: list index out of range

Thank you all!

You have two issues here. The first is that you're a little confused about list indexes. Lists in python are "zero-indexed" meaning that to get the first element of a list named L you need to do L[0] . Similarly, to get the second, like you need, you do L[1] .

The other issue is that all elements from sys.argv are going to be strings, so checking the type won't work. You should try to cast the piece of user input as an int inside a try block and catch a ValueError . It'd look something like this:

if __name__ == '__main__':

    if len(sys.argv) < 2 or len(sys.argv) > 2:
        help()

    else:
        try:
            insert_by_user = int(sys.argv[1])
            print(PWrand(insert_by_user))
        except ValueError:
            print("It need to be an Int!")

The code inside the except ValueError: block will only be executed if the user's input cannot be properly cast to an integer.

It's because the first if catch every list that has less than 2 elements or everything that has more than 2 elements, so the elif is catching everything that has exactly 2 elements, which will be stored in the position 0 and 1.

if len(sys.argv) is not 2:
    help()

else:
   user_input = sys.argv[1].decode()
   if not user_input.isnumeric():
      print("It need to be an Int!")
   else:
       user_input = int(user_input)

should fix it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM