Vadim Kantorov
Vadim Kantorov

Reputation: 1144

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?

Upvotes: 1

Views: 653

Answers (1)

Antwane
Antwane

Reputation: 22658

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.

Upvotes: 1

Related Questions