pythonargvoptional-arguments

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


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.


Solution

  • 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.