How to use *args in a function?

2019-08-04 07:16发布

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.

2条回答
迷人小祖宗
2楼-- · 2019-08-04 07:26

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.

查看更多
别忘想泡老子
3楼-- · 2019-08-04 07:34

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.

查看更多
登录 后发表回答