Search code examples
pythonargparseyoutube-dl

Passing configs from `.txt` file into argparse? (Similar to youtube-dl's `--config-location`)


I have a program with ~20 configs, which I would like to be accessed from the command-line via argparse, either by something like --config_1 'This is the first config' or --config-location <path_to_config_file>, where the path to the config file would be a .txt of form:

--config_1 'This is the first config'
--config_2 '2nd Config'
--config_3 3
...

Currently, my code looks something like:

parser = argparse.ArgumentParser()
parser.add_argument('--config_1')
args = vars(parser.parse_args())

This approach was inspired by youtube-dl's --config-location. If there's a better way to accomplish what I'm trying to do, suggestions are also appreciated and welcome. Thank you for reading!


Solution

  • argparse supports something similar out of the box.

    parser = ArgumentParser(fromfile_prefix_chars='@')
    parser.parse_args()
    

    Now any argument starting with @ will be treated as a filename to be read, which each line being treated as a separate argument. This would require your file to look like

    --config_1
    This is the first config
    --config_2
    2nd Config
    --config_3
    3
    ...
    

    instead.

    What youtube-dl does is simply open the file, read its contents, and split it on whitespace similar to how the shell would.