Python 'if __name__ == "__main__" 的目的:'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23000075/
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:06:56  来源:igfitidea点击:

Purpose of 'if __name__ == "__main__":'

pythonmain

提问by Chris Headleand

I am trying to understand some code I found which reads command line arguments (attached below). My concern is what purpose of the "if __name__ == __main__"line is...

我试图理解我发现的一些读取命令行参数的代码(附在下面)。我关心的是这条"if __name__ == __main__"线的目的是什么......

Why would I use that line instead of just using the code below, main(sys.argv[1:]). What extra use does it provide?

为什么我要使用该行而不是仅使用下面的代码,main(sys.argv[1:]). 它提供什么额外用途?

import sys, getopt

def main(argv):
   inputfile = ''
   outputfile = ''
   try:
      opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
   except getopt.GetoptError:
      print 'test.py -i <inputfile> -o <outputfile>'
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print 'test.py -i <inputfile> -o <outputfile>'
         sys.exit()
      elif opt in ("-i", "--ifile"):
         inputfile = arg
      elif opt in ("-o", "--ofile"):
         outputfile = arg
   print 'Input file is "', inputfile
   print 'Output file is "', outputfile

if __name__ == "__main__":
   main(sys.argv[1:])

采纳答案by kindall

Well, imagine that someone else wants to use the functions in your module in their own program. They import your module... and it starts doing its own thing!

好吧,想象一下其他人想在他们自己的程序中使用您模块中的函数。他们导入你的模块……然后它开始做自己的事情!

With the if __name__ == "__main__", this doesn't happen. Your module only "does its thing" if it's run as the mainmodule. Otherwise it behaves like a library. It encourages code reuse by making it easier.

使用if __name__ == "__main__",这不会发生。如果您的模块作为模块运行,则您的模块仅“做它的事” 。否则它的行为就像一个图书馆。它通过简化代码来鼓励代码重用。

(As @Sheng mentions, you may want to import the module into another script yourself for testing purposes.)

(正如@Sheng 提到的,您可能希望自己将模块导入另一个脚本以进行测试。)

回答by Sheng

It is for unit test proposes.

它用于单元测试建议。

If you are running this script directly, it will execute the ifblock. So you could do some unit test work here. But if you are importing this file as a module, you do not want this part to execute.

如果您直接运行此脚本,它将执行该if块。所以你可以在这里做一些单元测试工作。但是,如果您将此文件作为模块导入,则您不希望执行此部分。

It is similar to the main function in Java. In every Java class, you could have a main function for unit test. But the class is imported/used as a module, the main function would not be executed.

它类似于 Java 中的 main 函数。在每个 Java 类中,您都可以有一个用于单元测试的 main 函数。但是该类作为模块导入/使用,主函数不会被执行。

Generally, if you're using this script directly, it will run the ifblock. Otherwise, someone would like to use this file as a library of function/class, and the test case namemakes sure this code would not bother users.

通常,如果您直接使用此脚本,它将运行该if块。否则,有人想将此文件用作函数/类库,并且测试用例名称确保此代码不会打扰用户。

回答by g.d.d.c

The if __name__ == '__main__'convention in Python is intended to allow you to write code that can be run directly, or imported.

if __name__ == '__main__'Python 中的约定旨在允许您编写可以直接运行或导入的代码。

If you import it, that ifblock is not executed. If you run python.exe myscript.pyit is.

如果导入它,if则不会执行该块。如果你运行python.exe myscript.py它。

回答by Andrew Clark

This is the idiomatic way to tell whether the Python module was executed as a script, or imported from another module. You will only enter the if __name__ == "__main__"block if the file was executed as a script (aka, it is the main module).

这是判断 Python 模块是作为脚本执行还是从另一个模块导入的惯用方法。if __name__ == "__main__"如果文件作为脚本(也就是主模块)执行,您将只进入该块。