How To Use *args In A Function?
This may be a basic question, but unfortunately I was not able to get anything while searching. I have a function which uses *args to capture arguments when the function is run on
Solution 1:
sys.argv[1:]
will give you all commandline arguments as a list.
So you could do func(*sys.argv[1:])
in your code to receive all the arguments. However, there is no good reason to use varargs - just make the function accept a list args
and pass sys.argv[1:]
directly.
Solution 2:
You would use similar syntax when calling the function:
func(*sys.argv[1:])
Here the *
before the sys.argv
list expands the list into separate arguments.
The sys.argv
list itself contains all arguments found on the command line, including the script name; slicing it from the second item onwards gives you all the options passed in without the script name.
Post a Comment for "How To Use *args In A Function?"