omni-us / jsonargparse

Implement minimal boilerplate CLIs derived from type hints and parse from command line, config files and environment variables
https://jsonargparse.readthedocs.io
MIT License
314 stars 42 forks source link

How to save config to .yaml from within main? #477

Closed alexkrz closed 5 months ago

alexkrz commented 5 months ago

Hello,

for several use cases I want to save the config from within the main function. For example when I parse directories with omegaconf, I want to store the config to the parsed output directory. Is there some way to access the config from within the main function and save it to a .yaml file? Any hints are appreciated.

mauvilsa commented 5 months ago

To save the config it is necessary to have access to the parser object, so not currently possible by using jsonargparse.CLI. But still possible to do without having to manually build the parser. For example you can:

parser = jsonargparse.capture_parser(lambda: jsonargparse.CLI(...))
cfg = parser.parse_args()
parser.save(cfg, "path/where/to/save/config.yaml")
...

Certainly doing this means that you also have to call instantiate_classes if needed, and run a callable, which is what jsonargparse.CLI does automatically.

alexkrz commented 5 months ago

Hi, thanks for the quick response! The parser.save() method is what I was looking for. And the capture_parser() method also looks very useful!