处理argparse冲突 [英] Handling argparse conflicts
问题描述
如果我导入Python 模块已经使用 argparse ,但是,我也想在脚本中使用 argparse ...我应该如何去做?
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?
使用以下代码并使用-t标志调用脚本时,我收到无法识别的参数错误:
I'm receiving a unrecognized arguments error when using the following code and invoking the script with a -t flag:
代码段:
#!/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')
错误:
unrecognized arguments: -t foobar
推荐答案
您需要使用
if __name__ == '__main__':
...
针对它运行初始化代码,例如在导入时解析参数.参见 if __name__ == "__main__":
做什么?.
against it running initialization code such as argument parsing on import. See What does if __name__ == "__main__":
do?.
所以,在您的conflicting_module
做
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.
如果conflicting_module
中的解析是应用程序配置的必需部分,请考虑使用
If the parsing in conflicting_module
is a mandatory part of application configuration, consider using
args, rest = parser.parse_known_args()
在主模块中,然后将rest
传递给conflicting_module
,在其中将None
或rest
传递给parse_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)
那还是有点不好的风格,实际上conflicting_module
中的类和函数将理想地从主模块接收解析后的配置参数,该参数将负责解析它们.
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.
这篇关于处理argparse冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!