Handling argparse conflicts

北战南征 提交于 2019-12-13 23:34:49

问题


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 unrecognized arguments error when using the following code and invoking the script with a -t flag:

Snippet:

#!/usr/bin/env python

....
import conflicting_module
import argparse
...

#################################
# Step 0: Configure settings... #
#################################
parser = argparse.ArgumentParser(description='Process command line options.')
parser.add_argument('--test', '-t')

Error:

 unrecognized arguments: -t foobar

回答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.



来源:https://stackoverflow.com/questions/36007990/handling-argparse-conflicts

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!