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 the command line.
An basic structure is given below :
def func(*args):
<code starts>
...
</code ends>
func("arg1", "arg2", "arg3")
The problem here is, the code works if I pass the arguments in the code file itself as seen in the above snippet. I was looking on how to actually run this code from command line with the arguments are below :
# python <file.py> arg1 arg2 arg3
For that, I understand that I should change the line 'func("arg1", "arg2", "arg3")' in the code file itself, but I'm not sure how it is.
Can someone please point out how I can correct this.
Thanks a lot
NOTE: Both the solutions worked, yes both are the same. Its a pity I can't accept both answers.
You would use similar syntax when calling the function:
Here the
*
before thesys.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.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 listargs
and passsys.argv[1:]
directly.