How to set an optional argument for function in python when taking value by sys.argv

340 views Asked by At

I am writing a program to take 3 arguments from users. The former two arguments are integer, and the third argument is a string and optional.

I know that None is used as a null default for optional arguments, so I tried the following:

def main(w, l, s=None):
    variable_1 = w
    variable_2 = l
    variable_3 = s
...
...

main(int(sys.argv[1]), int(sys.argv[2]), sys.argv[3])

However, if I put the third value isn't put, then the following error happens.

IndexError: list index out of range

I believe it happens because the check for optional argument comes later than the timing that the system found the length of sys.argv array is not long enough. So, how should I set the optional argument by using None as a default in a correct way in this case? Thanks for reading my question.

2

There are 2 answers

0
Wired Hack On BEST ANSWER

You get IndexError: list index out of range because it tries to take the third argument from sys.argv. But if you don't provide the third argument, It tries to pass the third argument to the function, which doesn't exists. To fix this you could do something like this-

def main(w, l, s = None):
    variable_1 = w
    variable_2 = l
    variable_3 = s
...
...

if len(sys.argv) == 3:
    main(int(sys.argv[1]), int(sys.argv[2]), sys.argv[3])
else:
    main(int(sys.argv[1]), int(sys.argv[2]), None)

This will only take the argument if it exists, else it will assign None to variable_3.

1
Alex On

You have to assume the possibility there is no third argument given. I would do it maybe like follows:

def main(argument):
    variable_1 = int(argument[0])
    variable_2 = int(argument[1])
    variable_3 = argument[2] if len(argument)>1 else None
...
...

main(sys.argv)