Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

python - How to have one mandatory and two optional positional arguments?

I need to run a python file as follows

python runnning_program.py argument1 [argument2] [argument3]

def main(argument1,argument2 = default2, argument3 = default2):
   code


if __name__ == '__main__': 
   ap = argparse.ArgumentParser()
   ap.add_argument("argument1")
   kwargs = vars(ap.parse_args())
   main(**kwargs)

How to add argument2 and argument3 as optional positional arguments?

question from:https://stackoverflow.com/questions/65854638/how-to-have-one-mandatory-and-two-optional-positional-arguments

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Unfortunately, this does not work.

To elaborate a little: Positional arguments are mandatory. The quick take-away is, that a function in Python can always (and will always) be treated as having the following signature:

def some_function(*args, **kwargs):

This implies that positional arguments are basically just a list of arguments to the interpreter and will be expanded when passed to the function. Therefore, all positional arguments need to be present when calling the function.

That is a huge difference to how named arguments are passed ("keyword arguments"): They are a dictionary of the kind

{'parameter_name': 'parameter_value'}

They are always present as they get defined by having a default value.

To get back to your original issue: When calling your function, the option to pass kwargs by position instead of by name may help you.

so, instead of

main(argument1, argument2 = 'default2', argument3 = 'default3')

you can always call

main(argument1, 'default2', 'default3') instead.

Also, you may want to have a look at the argparse library.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...