Python:如果 __name__ == '__main__' 之后导入和初始化 Argparse?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27957373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:32:00  来源:igfitidea点击:

Python: Import And Initialize Argparse After if __name__ == '__main__'?

pythonscripting

提问by Daniel

If I am using argparse and an if __name__ == '__main__'test in a script that I would also like to use as a module, should I import argparse under that test and then initialize it? None of the style guides I have found mention using argparse in scripts and many examples of argparse scripting do not use the 'if name' test or use it differently. Here is what I have been going with so far:

如果我if __name__ == '__main__'在脚本中使用 argparse 和一个我也想用作模块的测试,我应该在该测试下导入 argparse 然后初始化它吗?我发现的任何样式指南都没有提到在脚本中使用 argparse,许多 argparse 脚本示例不使用“if name”测试或以不同方式使用它。到目前为止,这是我一直在做的事情:

#! /usr/bin/env python

def main(name):
    print('Hello, %s!' % name)

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description = 'Say hello')
    parser.add_argument('name', help='your name, enter it')
    args = parser.parse_args()

    main(args.name)

Should I import argparse with my other modules at the top and configure it in the body of the script instead?

我应该将 argparse 与顶部的其他模块一起导入并在脚本正文中进行配置吗?

采纳答案by BrenBarn

I would put the import at the top, but leave the code that uses it inside the if __name__block:

我会将导入放在顶部,但将使用它的代码保留在if __name__块内:

import argparse

# other code. . .

def main(name):
    print('Hello, %s!' % name)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description = 'Say hello')
    parser.add_argument('name', help='your name, enter it')
    args = parser.parse_args()

    main(args.name)

Putting the imports at the top clarifies what modules your module uses. Importing argpase even when you don't use it will have negligible performance impact.

将导入放在顶部可以阐明您的模块使用哪些模块。即使您不使用 argpase,也导入它对性能的影响可以忽略不计。

回答by 101

It's fine to put the import argparsewithin the if __name__ == '__main__'block if argparseis only referred to within that block. Obviously the code within that block won't run if your module is imported by another module, so that module would have to provide it's own argument for main(possibly using it's own instance of ArgumentParser).

它的优良把import argparse该内if __name__ == '__main__'块,如果argparse该块内只提到。显然,如果您的模块是由另一个模块导入的,那么该块中的代码将不会运行,因此该模块必须提供它自己的参数main(可能使用它自己的 实例ArgumentParser)。