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
356 views
in Technique[技术] by (71.8m points)

python - Is it possible to use argparse to capture an arbitrary set of optional arguments?

Is it possible to use argparse to capture an arbitrary set of optional arguments?

For example both the following should be accepted as inputs:

python script.py required_arg1 --var1 value1 --var2 value2 --var3 value3

python script.py required_arg1 --varA valueA --var2 value2 --varB valueB

a priori I don't know what optional arguments would be specified receive but would handle them accordingly.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This is kind of a hackish way, but it works well:

Check, which arguments are not added and add them

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("foo")
parser.add_argument("-bar", type=int)
# parser can have any arguments, whatever you want!

parsed, unknown = parser.parse_known_args() # this is an 'internal' method
# which returns 'parsed', the same as what parse_args() would return
# and 'unknown', the remainder of that
# the difference to parse_args() is that it does not exit when it finds redundant arguments

for arg in unknown:
    if arg.startswith(("-", "--")):
        # you can pass any arguments to add_argument
        parser.add_argument(arg.split('=')[0], type=<your type>, ...)

args = parser.parse_args()

For example:

python3 arbitrary_parser.py ha -bar 12 -extra1 value1 -extra2 value2

Then the result would be

args = Namespace(bar=12, foo='ha', extra1='value1' extra2='value2')

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

...