Beispiel #1
0
 def read_configure_arguments(
         self,
         document: str,
         reader: dict_readers.AbstractDictReader,
         parser: OriginalAP = None
 ) -> Namespace:
     """Read the given document as given style and return the parameters."""
     parser = if_none_then(parser, ArgumentParser())
     contents = reader.to_normalized_dict(document)
     args: List[str] = []
     for key, val in contents.items():
         if val is None:
             continue
         args.append(key)
         if val is True or val is False:
             # maybe nargs = 0
             pass
         elif isinstance(val, (list, tuple)):
             for v in val:
                 args.append(str(v))
         else:
             args.append(str(val))
     self.add_arguments_to_parser(parser)
     name_space = parser.parse_args(args)
     return Namespace(name_space)
Beispiel #2
0
 def _add_arguments_to_writer(
         self,
         writer: dict_writers.AbstractDictWriter
 ) -> None:
     self._add_arguments_recursively(root=self, parser=ArgumentParser(), writer=writer,
                                     parent_names=[''], parent_dists=[], argument_prefixes=[],
                                     propagate_data=dict(), prohibited_args=dict(),
                                     no_provides=set())
Beispiel #3
0
        back_tire_params._update({'radius': params.tire_radius + 1.0})
        # of course you can use normal access to the attribute
        back_tire_params.value *= 2
        self._back_tires = [Tire(back_tire_params) for i in range(2)]

    def print_spec(self) -> None:
        print('Car: ')
        print('front tires: {}'.format(', '.join([str(tire) for tire in self._front_tires])))
        print('back tires: {}'.format(', '.join([str(tire) for tire in self._back_tires])))
        if self._numbers is not None:
            print('by the way, I like {} hahaha'.format(', '.join([str(n) for n in self._numbers])))


if __name__ == '__main__':
    # set a root argument provider (same as other argument providers)
    args_provider = ArgsProvider(
        child_providers=[ChildProvider(Car)]
    )

    # quite usual argparse way except *new code* line
    parser = ArgumentParser()
    parser.add_argument('-V', '--version', action='version', version='v1.0')
    args_provider.add_arguments_to_parser(parser)  # *new code*
    params = parser.parse_args()

    # now you have ALL parameters including child and grandchild arguments
    print(params)

    car = Car(params.Car)
    car.print_spec()
Beispiel #4
0
from hiargparse import ArgumentParser, Namespace

# just same as example.py
from example import Son

if __name__ == '__main__':
    # Make a instance of Son, which has hiargparse.ArgsProvider,
    # without any program arguments.
    # This example is especially useful when you distribute your hi-argparsed program
    # and someone want to use your program without any accessing to his program arguments.

    # first of all, once try print() and you'll see the all parameters
    # (of cource this is not necessary)
    parser = ArgumentParser()
    Son.get_args_provider().add_arguments_to_parser(parser)
    print(parser.get_default_parameters()
          )  # you can call parse_args(args=[]) instead of this line

    # then here we go
    son_params = Namespace(
        dict(hoge=42, huga='hey', piyo=0.90, GS=dict(huga='hey', piyo=0.91)))
    son = Son(son_params)
    son.print_()

    # tired to write propagate args (like huga='hey') many times
    # or values you want to leave default (like hoge=42) ?
    # tell your args_provider to propagate args :)
    args_provider = Son.get_args_provider()
    parser = ArgumentParser()
    parser.add_arguments_from_provider(args_provider)
    son_params = parser.get_default_parameters()  # get default parameters
from hiargparse import ArgsProvider, Arg, ChildProvider, ArgumentParser

child = ArgsProvider(args=[Arg('baz', default=42)])
root = ArgsProvider(
    args=[Arg('foo', default='bar')],
    child_providers=[ChildProvider(provider=child, name='child')])
parser = ArgumentParser()
parser.add_arguments_from_provider(root)
print(parser.parse_args())
Beispiel #6
0
            ]
        )

    def __init__(self, params: Namespace) -> None:
        self._params = params
        self._gson = GrandSon(params.GS)

    def print_(self) -> None:
        print(self._params.hoge, self._params.huga, self._params.piyo)
        self._gson.print_()


if __name__ == '__main__':
    # set a root argument provider (same as other argument providers)
    args_provider = ArgsProvider(
        args=[Arg(name='foo', default='bar')],
        child_providers=[ChildProvider(Son)]
    )

    # quite usual argparse way except *new code* line
    parser = ArgumentParser()
    parser.add_argument('-V', '--version', action='version', version='v1.0')
    parser.add_arguments_from_provider(args_provider)  # *new code*
    params = parser.parse_args()

    # now you have ALL parameters including child and grandchild arguments
    # please try to execute with --help
    print(params.foo)
    son = Son(params.Son)
    son.print_()
            Arg('file-type', default='yaml', choices=file_type_names),
            # write-to argument
            Arg('write-to',
                type=Path,
                help=
                '%(default-text)s Write a configure file in the given path and exit. '
                ),
            # read-from argument
            Arg('read-from',
                type=Path,
                help='%(default-text)s Read from the given configure file. '),
        ],
        child_providers=[ChildProvider(Son)])

    # parse arguments as usual
    parser = ArgumentParser()
    parser.add_argument('-V', '--version', action='version', version='v1.0')
    parser.add_arguments_from_provider(args_provider)
    params = parser.parse_args()

    # write to / read from a file
    file_type = ConfigureFileType[params.file_type]
    if params.write_to is not None:
        path_w: Path = params.write_to
        # write configure arguments to the given file as the given type
        with path_w.open('w') as f:
            f.write(
                args_provider.write_out_configure_arguments(
                    file_type.get_writer()))
        # When you want to write out a configure file,
        # usually you want to stop this program, fill in