How to use *args in a function?

送分小仙女□ 提交于 2019-12-24 13:41:41

问题


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.


回答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.




回答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.



来源:https://stackoverflow.com/questions/19767604/how-to-use-args-in-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!