Skip to content Skip to sidebar Skip to footer

Handling Argparse Conflicts

If I import a Python module that is already using argparse, however, I would like to use argparse in my script as well ...how should I go about doing this? I'm receiving a unrecogn

Solution 1:

You need to guard your imported modules with

if __name__ == '__main__':
    ...

against it running initialization code such as argument parsing on import. See What does if __name__ == "__main__": do?.

So, in your conflicting_module do

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Process command line options in conflicting_module.py.')
    parser.add_argument('--conflicting', '-c')
    ...

instead of just creating the parser globally.

If the parsing in conflicting_module is a mandatory part of application configuration, consider using

args, rest = parser.parse_known_args()

in your main module and passing rest to conflicting_module, where you'd pass either None or rest to parse_args:

args = parser.parse_args(rest)

That is still a bit bad style and actually the classes and functions in conflicting_module would ideally receive parsed configuration arguments from your main module, which would be responsible for parsing them.


Post a Comment for "Handling Argparse Conflicts"