这样做做什么,为什么应该包括:if语句?

if __name__ == "__main__":
    print("Hello, World!")

如果你试图结束一个问题 如果你想要结束一个问题 在那里有人应该应该 使用这个学说,而不是,是不是, 考虑关闭作为 重复的为什么Python在我进口时 运行我的模块? 我该如何阻止它?。而对于某些问题,如果有人只是没有调用任何函数,或者错误地期望指定函数main自动用作切入点,使用当我启动 Python 脚本时, 主函数为何不运行? 脚本从哪里开始运行 ?.


当前回答

简单的答案就是代码 代码是写在如果名称名称名称名称名称 == "主要":如果您在其它文件中导入的话, 将不会执行 。

其他回答

当你import具有此条件的代码, 它会返回False(除进口编码外),但将返回True将要运行的代码的代码 。

当您在本地交互运行 Python 时__name__变量的变量被指定值__main__同样,当您从命令行执行 Python 模块时,而不是将它导入到另一个模块中时,它__name__属性的属性被指定值__main__,而不是模块的实际名称。这样,模块可以查看自己的__name__用于确定它们是如何使用的值, 无论是作为对其它程序的支持还是作为从命令行执行的主要应用程序。 因此, 在 Python 模块中, 下列语系非常常见 :

if __name__ == '__main__':
    # Do something appropriate here, like calling a
    # main() function defined elsewhere in this module.
    main()
else:
    # Do nothing. This module has been imported by another
    # module that wants to make use of the functions,
    # classes and other useful bits it has defined.

缩略Python 主函数是一个程序的起始点。当程序运行时, Python 口译员会按顺序运行代码。主要函数只有在作为 Python 程序运行时才执行...

def main():
    print("I am in the function")

print("I am out of the function")

当运行脚本显示时 :

I am out of the function

而不是代码"我是在函数"。

这是因为我们没有宣布调用功能“if_name”主要".

使用时使用:

def main():
    print("I am in the function")

if __name__ == "__main__":
    main()

print("I am out of the function")

输出等于

I am in the function
I am out of the function

在皮顿if__name__== "__main__"允许您作为可重复使用的模块或独立程序运行 Python 文件。

当 Python 口译员读取源文件时, 它会执行其中的所有代码。 当 Python 运行“ 源文件” 作为主程序时, 它会设置特殊变量__name__要有一个值"__main__".

当您执行主函数时,它会读取if用来检查__name__等于__main__.

什么是什么东西if __name__ == "__main__":是吗?

__name__是一个全球变量(在 Python 中,在模块模块级别)存在于所有命名空间的所有命名空间中。它通常是模块的名称(作为str类型))

然而,作为唯一的特殊情况,无论你运行的 Python 程序,就像我的代码。 py:

python mycode.py

以其他匿名的全域命名空间被指定为'__main__'至其__name__.

因此,包括最后一行

if __name__ == '__main__':
    main()
  • 在我的代码.py脚本的结尾,
  • 当它是由 Python 进程运行的初级切入点模块时,

将会导致您的脚本有独特的定义main要运行的函数。

使用此构造的另一个好处是:您也可以将代码作为模块导入到另一个脚本中,然后运行主函数,如果且当您的程序决定:

import mycode
# ... any amount of other code
mycode.main()

if __name__ == "__main__":无法在导入文件时运行不需要的代码 。

例如,这是test1.pyif __name__ == "__main__"::

# "test1.py"

def hello()
    print("Hello")

hello()

还有test2.py进口test1.py:

# "test2.py"

import test1 # Here


然后,当奔跑的时候,test2.py, 1个Hello打印是因为不需要的代码hello()test1.py同时运行 :

python test2.py
Hello

当然,你可以打给test1.hello()test2.py:

# "test2.py"

import test1

test1.hello() # Here

然后,当奔跑的时候,test2, Hello已经打印 :

python test2.py
Hello
Hello

现在,添加if __name__ == "__main__":test1.py并放hello()在其之下:

# "test1.py"

def hello()
    print("Hello")

if __name__ == "__main__":
    hello()

这是test2.py:

# "test2.py"

import test1

test1.hello()

然后,当奔跑的时候,test2.py, 只有一个Hello打印是因为if __name__ == "__main__":防止要运行不需要的代码hello()何时test2.py进口进口进口test1.py:

python test2.py
Hello

此外,是否test1.py拥有if __name__ == "__main__":或非:

# "test1.py"

def hello()
    print("Hello")

if __name__ == "__main__":
    hello()
# "test1.py"

def hello()
    print("Hello")

hello()

一个Hello运行时正确打印test1.py:

python test1.py
Hello