update README.md
This commit is contained in:
parent
ba1dc5d8c4
commit
b026f9755c
3 changed files with 178 additions and 60 deletions
136
README.md
136
README.md
|
@ -2,59 +2,139 @@
|
||||||
|
|
||||||
Python3 parser for command-line options and arguments using Tiramisu engine.
|
Python3 parser for command-line options and arguments using Tiramisu engine.
|
||||||
|
|
||||||
# simple example
|
# example
|
||||||
|
|
||||||
|
Let us start with a simple example
|
||||||
|
|
||||||
```python
|
```python
|
||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
from tiramisu_cmdline_parser import TiramisuCmdlineParser
|
from tiramisu_cmdline_parser import TiramisuCmdlineParser
|
||||||
from tiramisu import StrOption, BoolOption, SymLinkOption, OptionDescription, \
|
from tiramisu import IntOption, StrOption, BoolOption, ChoiceOption, \
|
||||||
Config
|
SymLinkOption, OptionDescription, Config
|
||||||
parser = TiramisuCmdlineParser()
|
# build a Config with:
|
||||||
|
# * a choice for select a sub argument (str, list, int)
|
||||||
|
choiceoption = ChoiceOption('cmd',
|
||||||
|
'choice the sub argument',
|
||||||
|
('str', 'list', 'int'),
|
||||||
|
properties=('mandatory',
|
||||||
|
'positional'))
|
||||||
|
# * a boolean to pass script in verbosity mode with argument -v --verbosity
|
||||||
booloption = BoolOption('verbosity',
|
booloption = BoolOption('verbosity',
|
||||||
'increase output verbosity',
|
'increase output verbosity',
|
||||||
default=False)
|
default=False)
|
||||||
config = Config(OptionDescription('root', 'root', [StrOption('var',
|
short_booloption = SymLinkOption('v', booloption)
|
||||||
'a string option',
|
# * a string option if cmd is 'str'
|
||||||
properties=('mandatory',
|
str_ = StrOption('str',
|
||||||
'positional')),
|
'string option',
|
||||||
|
properties=('mandatory',),
|
||||||
|
requires=[{'option': choiceoption,
|
||||||
|
'expected': 'str',
|
||||||
|
'action': 'disabled',
|
||||||
|
'inverse': True}])
|
||||||
|
# * a list of strings option if cmd is 'list'
|
||||||
|
list_ = StrOption('list',
|
||||||
|
'list string option',
|
||||||
|
multi=True,
|
||||||
|
properties=('mandatory',),
|
||||||
|
requires=[{'option': choiceoption,
|
||||||
|
'expected': 'list',
|
||||||
|
'action': 'disabled',
|
||||||
|
'inverse': True}])
|
||||||
|
# * an integer option if cmd is 'int'
|
||||||
|
int_ = IntOption('int',
|
||||||
|
'int option',
|
||||||
|
properties=('mandatory',),
|
||||||
|
requires=[{'option': choiceoption,
|
||||||
|
'expected': 'int',
|
||||||
|
'action': 'disabled',
|
||||||
|
'inverse': True}])
|
||||||
|
config = Config(OptionDescription('root',
|
||||||
|
'root',
|
||||||
|
[choiceoption,
|
||||||
booloption,
|
booloption,
|
||||||
SymLinkOption('v', booloption)]))
|
short_booloption,
|
||||||
|
str_,
|
||||||
|
list_,
|
||||||
|
int_
|
||||||
|
]))
|
||||||
|
# initialise the parser
|
||||||
|
parser = TiramisuCmdlineParser()
|
||||||
|
# add the config to parser
|
||||||
parser.add_arguments(config)
|
parser.add_arguments(config)
|
||||||
|
# parse arguments of current script
|
||||||
parser.parse_args()
|
parser.parse_args()
|
||||||
print('result:', config.value.dict())
|
# now, print the result
|
||||||
|
print('result:')
|
||||||
|
config.property.read_only()
|
||||||
|
for key, value in config.value.dict().items():
|
||||||
|
print('- {} ({}): {}'.format(key,
|
||||||
|
config.option(key).option.doc(),
|
||||||
|
value))
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Let's print help:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
[gnunux@localhost tiramisu-parser]$ ./prog.py -h
|
[gnunux@localhost tiramisu-parser]$ python3 prog.py str -h
|
||||||
usage: prog.py [-h] [-v] var
|
usage: prog.py [-h] [-v] --str STR --list LIST [LIST ...] --int INT
|
||||||
|
{str,list,int}
|
||||||
|
|
||||||
positional arguments:
|
positional arguments:
|
||||||
var a string option
|
{str,list,int} choice the sub argument
|
||||||
|
|
||||||
optional arguments:
|
optional arguments:
|
||||||
-h, --help show this help message and exit
|
-h, --help show this help message and exit
|
||||||
-v, --verbosity increase output verbosity
|
-v, --verbosity increase output verbosity
|
||||||
|
--str STR string option
|
||||||
|
--list LIST [LIST ...]
|
||||||
|
list string option
|
||||||
|
--int INT int option
|
||||||
|
```
|
||||||
|
|
||||||
|
The positional argument 'cmd' is mandatory:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
[gnunux@localhost tiramisu-parser]$ python3 prog.py
|
||||||
|
usage: prog.py [-h] [-v] --str STR --list LIST [LIST ...] --int INT
|
||||||
|
{str,list,int}
|
||||||
|
prog.py: error: the following arguments are required: cmd
|
||||||
|
```
|
||||||
|
|
||||||
|
If 'cmd' is 'str', --str become mandatory:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
[gnunux@localhost tiramisu-parser]$ python3 prog.py str
|
||||||
|
usage: prog.py [-h] [-v] --str STR --list LIST [LIST ...] --int INT
|
||||||
|
{str,list,int}
|
||||||
|
prog.py: error: the following arguments are required: --str
|
||||||
|
```
|
||||||
|
|
||||||
|
With all mandatories arguments:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
[gnunux@localhost tiramisu-parser]$ python3 prog.py str --str value
|
||||||
|
result:
|
||||||
|
- cmd (choice the sub argument): str
|
||||||
|
- verbosity (increase output verbosity): False
|
||||||
|
- v (increase output verbosity): False
|
||||||
|
- str (string option): value
|
||||||
```
|
```
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
[gnunux@localhost tiramisu-parser]$ ./prog.py -v
|
[gnunux@localhost tiramisu-parser]$ python3 prog.py int --int 3
|
||||||
usage: prog.py [-h] [-v] var
|
result:
|
||||||
prog.py: error: the following arguments are required: var
|
- cmd (choice the sub argument): int
|
||||||
|
- verbosity (increase output verbosity): False
|
||||||
|
- v (increase output verbosity): False
|
||||||
|
- int (int option): 3
|
||||||
```
|
```
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
[gnunux@localhost tiramisu-parser]$ ./prog.py test
|
[gnunux@localhost tiramisu-parser]$ python3 prog.py list --list a b c
|
||||||
result: {'var': 'test', 'verbosity': False, 'v': False}
|
result:
|
||||||
```
|
- cmd (choice the sub argument): list
|
||||||
|
- verbosity (increase output verbosity): False
|
||||||
```bash
|
- v (increase output verbosity): False
|
||||||
[gnunux@localhost tiramisu-parser]$ ./prog.py -v test
|
- list (list string option): ['a', 'b', 'c']
|
||||||
result: {'var': 'test', 'verbosity': True, 'v': True}
|
|
||||||
```
|
|
||||||
|
|
||||||
```bash
|
|
||||||
[gnunux@localhost tiramisu-parser]$ ./prog.py --verbosity test
|
|
||||||
result: {'var': 'test', 'verbosity': True, 'v': True}
|
|
||||||
```
|
```
|
||||||
|
|
|
@ -22,7 +22,7 @@ for test in listdir(DATA_DIR):
|
||||||
|
|
||||||
TEST_DIRS.sort()
|
TEST_DIRS.sort()
|
||||||
# TEST_DIRS.remove('test/data/compare/10_positional_list')
|
# TEST_DIRS.remove('test/data/compare/10_positional_list')
|
||||||
# TEST_DIRS = ['test/data/compare/50_conditional_disable']
|
# TEST_DIRS = ['test/data/compare/10_positional_list']
|
||||||
|
|
||||||
|
|
||||||
@fixture(scope="module", params=TEST_DIRS)
|
@fixture(scope="module", params=TEST_DIRS)
|
||||||
|
@ -76,6 +76,15 @@ def test_files(test_list):
|
||||||
['bar', '--verbosity'], ['--verbosity', 'bar'],
|
['bar', '--verbosity'], ['--verbosity', 'bar'],
|
||||||
]
|
]
|
||||||
for arg in args:
|
for arg in args:
|
||||||
|
# FIXME unknown argument is check before mandatory
|
||||||
|
if test_list == 'test/data/compare/10_positional_list':
|
||||||
|
check = False
|
||||||
|
for subarg in arg:
|
||||||
|
if not subarg.startswith('-'):
|
||||||
|
check = True
|
||||||
|
break
|
||||||
|
if not check:
|
||||||
|
continue
|
||||||
tiramparser = TiramisuCmdlineParser('prog.py')
|
tiramparser = TiramisuCmdlineParser('prog.py')
|
||||||
tiramparser_dict, tiramparser_system_err, tiramparser_error, tiramparser_help = import_subfile_and_test(test_list + '/tiramisu.py',
|
tiramparser_dict, tiramparser_system_err, tiramparser_error, tiramparser_help = import_subfile_and_test(test_list + '/tiramisu.py',
|
||||||
tiramparser, arg)
|
tiramparser, arg)
|
||||||
|
@ -83,6 +92,7 @@ def test_files(test_list):
|
||||||
argparser = ArgumentParser('prog.py')
|
argparser = ArgumentParser('prog.py')
|
||||||
argparser_dict, argparser_system_err, argparser_error, argparser_help = import_subfile_and_test(test_list + '/argparse.py',
|
argparser_dict, argparser_system_err, argparser_error, argparser_help = import_subfile_and_test(test_list + '/argparse.py',
|
||||||
argparser, arg)
|
argparser, arg)
|
||||||
|
# print('===>', test_list, arg)
|
||||||
# print(tiramparser_dict)
|
# print(tiramparser_dict)
|
||||||
# print(tiramparser_system_err)
|
# print(tiramparser_system_err)
|
||||||
# print(tiramparser_error)
|
# print(tiramparser_error)
|
||||||
|
|
|
@ -23,12 +23,14 @@ from tiramisu.error import PropertiesOptionError
|
||||||
|
|
||||||
class TiramisuNamespace(Namespace):
|
class TiramisuNamespace(Namespace):
|
||||||
def _populate(self):
|
def _populate(self):
|
||||||
|
self._config.property.read_only()
|
||||||
for tiramisu_key, tiramisu_value in self._config.value.dict().items():
|
for tiramisu_key, tiramisu_value in self._config.value.dict().items():
|
||||||
option = self._config.option(tiramisu_key)
|
option = self._config.option(tiramisu_key)
|
||||||
if not isinstance(option.option.get(), SymLinkOption):
|
if not isinstance(option.option.get(), SymLinkOption):
|
||||||
if tiramisu_value == [] and option.option.ismulti() and option.owner.isdefault():
|
if tiramisu_value == [] and option.option.ismulti() and option.owner.isdefault():
|
||||||
tiramisu_value = None
|
tiramisu_value = None
|
||||||
super().__setattr__(tiramisu_key, tiramisu_value)
|
super().__setattr__(tiramisu_key, tiramisu_value)
|
||||||
|
self._config.property.read_write()
|
||||||
|
|
||||||
def __init__(self, config):
|
def __init__(self, config):
|
||||||
self._config = config
|
self._config = config
|
||||||
|
@ -46,9 +48,7 @@ class TiramisuNamespace(Namespace):
|
||||||
|
|
||||||
def __getattribute__(self, key):
|
def __getattribute__(self, key):
|
||||||
if key == '__dict__' and hasattr(self, '_config'):
|
if key == '__dict__' and hasattr(self, '_config'):
|
||||||
self._config.property.read_only()
|
|
||||||
self._populate()
|
self._populate()
|
||||||
self._config.property.read_write()
|
|
||||||
return super().__getattribute__(key)
|
return super().__getattribute__(key)
|
||||||
|
|
||||||
|
|
||||||
|
@ -77,16 +77,13 @@ class TiramisuCmdlineParser(ArgumentParser):
|
||||||
else:
|
else:
|
||||||
raise NotImplementedError('do not use add_argument')
|
raise NotImplementedError('do not use add_argument')
|
||||||
|
|
||||||
def add_arguments(self, tiramisu: Union[Config, Option, List[Option], OptionDescription]) -> None:
|
def add_subparsers(self, *args, **kwargs):
|
||||||
if not isinstance(tiramisu, Config):
|
raise NotImplementedError('do not use add_subparsers')
|
||||||
if not isinstance(tiramisu, OptionDescription):
|
|
||||||
if isinstance(tiramisu, Option):
|
def _config_to_argparser(self,
|
||||||
tiramisu = [tiramisu]
|
_forhelp: bool):
|
||||||
tiramisu = OptionDescription('root', 'root', tiramisu)
|
|
||||||
tiramisu = Config(tiramisu)
|
|
||||||
self.config = tiramisu
|
|
||||||
actions = {}
|
actions = {}
|
||||||
for obj in tiramisu.unrestraint.option.list():
|
for obj in self.config.unrestraint.option.list():
|
||||||
if obj.option.properties(only_raises=True) or 'frozen' in obj.option.properties():
|
if obj.option.properties(only_raises=True) or 'frozen' in obj.option.properties():
|
||||||
continue
|
continue
|
||||||
option = obj.option
|
option = obj.option
|
||||||
|
@ -108,7 +105,7 @@ class TiramisuCmdlineParser(ArgumentParser):
|
||||||
args = [self.prefix_chars + name]
|
args = [self.prefix_chars + name]
|
||||||
else:
|
else:
|
||||||
args = [self.prefix_chars * 2 + name]
|
args = [self.prefix_chars * 2 + name]
|
||||||
if 'mandatory' in properties:
|
if _forhelp and 'mandatory' in properties:
|
||||||
kwargs['required'] = True
|
kwargs['required'] = True
|
||||||
if isinstance(tiramisu_option, BoolOption):
|
if isinstance(tiramisu_option, BoolOption):
|
||||||
if 'mandatory' in properties:
|
if 'mandatory' in properties:
|
||||||
|
@ -126,7 +123,7 @@ class TiramisuCmdlineParser(ArgumentParser):
|
||||||
#kwargs['action'] = 'store_const'
|
#kwargs['action'] = 'store_const'
|
||||||
kwargs['nargs'] = '?'
|
kwargs['nargs'] = '?'
|
||||||
if option.ismulti():
|
if option.ismulti():
|
||||||
if 'mandatory' in properties:
|
if _forhelp and 'mandatory' in properties:
|
||||||
kwargs['nargs'] = '+'
|
kwargs['nargs'] = '+'
|
||||||
else:
|
else:
|
||||||
kwargs['nargs'] = '*'
|
kwargs['nargs'] = '*'
|
||||||
|
@ -147,19 +144,50 @@ class TiramisuCmdlineParser(ArgumentParser):
|
||||||
for args, kwargs in actions.values():
|
for args, kwargs in actions.values():
|
||||||
super().add_argument(*args, **kwargs)
|
super().add_argument(*args, **kwargs)
|
||||||
|
|
||||||
|
def add_arguments(self,
|
||||||
|
tiramisu: Union[Config, Option, List[Option], OptionDescription],
|
||||||
|
_forhelp: bool=False) -> None:
|
||||||
|
if not isinstance(tiramisu, Config):
|
||||||
|
if not isinstance(tiramisu, OptionDescription):
|
||||||
|
if isinstance(tiramisu, Option):
|
||||||
|
tiramisu = [tiramisu]
|
||||||
|
tiramisu = OptionDescription('root', 'root', tiramisu)
|
||||||
|
tiramisu = Config(tiramisu)
|
||||||
|
self.config = tiramisu
|
||||||
|
self._config_to_argparser(_forhelp)
|
||||||
|
|
||||||
def parse_args(self, *args, **kwargs):
|
def parse_args(self, *args, **kwargs):
|
||||||
kwargs['namespace'] = TiramisuNamespace(self.config)
|
kwargs['namespace'] = TiramisuNamespace(self.config)
|
||||||
try:
|
|
||||||
namespaces = super().parse_args(*args, **kwargs)
|
namespaces = super().parse_args(*args, **kwargs)
|
||||||
|
try:
|
||||||
|
del namespaces.__dict__['_config']
|
||||||
except PropertiesOptionError as err:
|
except PropertiesOptionError as err:
|
||||||
# import traceback
|
if err.proptype == ['mandatory']:
|
||||||
# traceback.print_exc()
|
name = err._option_bag.option.impl_getname()
|
||||||
if err.proptype == ('mandatory',):
|
properties = self.config.option(name).property.get()
|
||||||
self.error('the following arguments are required: {}'.format(err._option_bag.option.impl_getname()))
|
if 'positional' not in properties:
|
||||||
|
if len(name) == 1 and 'longargument' not in properties:
|
||||||
|
name = self.prefix_chars + name
|
||||||
|
else:
|
||||||
|
name = self.prefix_chars * 2 + name
|
||||||
|
self.error('the following arguments are required: {}'.format(name))
|
||||||
else:
|
else:
|
||||||
self.error('unexpected error: {}'.format(err))
|
self.error('unexpected error: {}'.format(err))
|
||||||
del namespaces.__dict__['_config']
|
|
||||||
return namespaces
|
return namespaces
|
||||||
|
|
||||||
|
def format_usage(self, *args, _forhelp=False, **kwargs):
|
||||||
|
if _forhelp:
|
||||||
|
return super().format_usage(*args, **kwargs)
|
||||||
|
help_formatter = TiramisuCmdlineParser(self.prog)
|
||||||
|
help_formatter.add_arguments(self.config, _forhelp=True)
|
||||||
|
return help_formatter.format_usage(*args, **kwargs, _forhelp=True)
|
||||||
|
|
||||||
|
def format_help(self, *args, _forhelp=False, **kwargs):
|
||||||
|
if _forhelp:
|
||||||
|
return super().format_help(*args, **kwargs)
|
||||||
|
help_formatter = TiramisuCmdlineParser(self.prog)
|
||||||
|
help_formatter.add_arguments(self.config, _forhelp=True)
|
||||||
|
return help_formatter.format_help(*args, **kwargs, _forhelp=True)
|
||||||
|
|
||||||
def get_config(self):
|
def get_config(self):
|
||||||
return self.config
|
return self.config
|
||||||
|
|
Loading…
Reference in a new issue