简体   繁体   中英

How to parse CMake-style arguments with python argparse?

I am using argparse to parse arguments of form -D VAR=VALUE or --config VAR=VALUE like this:

cmd.add_argument('--config', '-D', action = 'append', default = [])

I'd also like to support CMake-style variable assignments of form -DVAR=VALUE .

Are there good ways to achieve it with argparse without resorting to manual sys.argv tinkering?

Yes, argparse supports all the common forms of cli arguments. Example:

import argparse
cmd = argparse.ArgumentParser()
cmd.add_argument('-D', action='append', default = [])
print(cmd.parse_args())

Usage:

$ python test_argparse.py -DVAR=val1 -DDEFINED_VAR -D ANOTHER_DEF -D VAR="string_val"
Namespace(D=['VAR=val1', 'DEFINED_VAR', 'ANOTHER_DEF', 'VAR=string_val'])

But you should probably set 2 different arguments to handle -D and --config options.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM