如果 __name__ == '__main__' python

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

if __name__ == '__main__' python

python

提问by Jaskaran Zap

I have go through so many articles regarding this

我已经阅读了很多关于此的文章

if __name__ == '__main__'

but didn't get it.. I am going to share you code please could you explain it more briefly..

但没有得到它.. 我要分享你的代码,请你能更简单地解释一下..

I have created one file "ab.py"

我创建了一个文件“ab.py”

def a():
    print('A function in ab file');

a()

the second file is "xy.py"

第二个文件是“xy.py”

import ab

def b():
    print('b function')

def x(): print ('s');

x()

if __name__ == "__main__" :b()

When i execute this code then this output is coming

当我执行此代码时,此输出即将到来

A function in ab file
s
b function

Now I want to know what does this mean, What is actually doing this code, Why we implement this? Our code is work without it also

现在我想知道这是什么意思,这段代码实际上在做什么,我们为什么要实现这个?我们的代码在没有它的情况下也能工作

if __name__ == "__main__" :b()

回答by Adam Hughes

You should get in the habit of using this almost always.

您应该养成几乎总是使用它的习惯。

Anything that comes after if __name__ == '__main__':will be run only when you explicitly run your file.

if __name__ == '__main__':仅当您明确运行文件时,才会运行后面的任何内容。

python myfile.py

However, if you import myfile.pyelsewhere:

但是,如果您myfile.py在其他地方导入:

import myfile

Nothing under if __name__ == '__main__':will be called.

下面什么if __name__ == '__main__':都不会被调用。

回答by joechoj

What is actually doing this code?

这段代码实际上在做什么?

When you execute xy.py, you import ab. The import statement runs the module on import, so ab's operations get executed before the remainder of xy's. Once finished with ab, it continues with xy.

当你执行 xy.py 时,你导入了 ab。import 语句在导入时运行模块,因此 ab 的操作在 xy 的其余部分之前执行。完成 ab 后,它继续执行 xy。

The interpreter keeps track of which scripts are running with __name__. When you run a script - no matter what you've named it - the interpreter calls it "__main__". That's how it keeps track of which script is the master file, the script that gets returned to after an external call to another script. (The 'home' script, you might say.) Any other script that's called from this 'main' script is assigned its filename as its __name__. Hence, the line if __name__ == "__main__" :is the interpreter's test to determine if it's running on the script it's looking at (parsing), or if it's temporarily peeking into another script. This gives the programmer flexibility to have the script behave differently if it's called externally.

解释器会跟踪正在运行的脚本__name__。当你运行一个脚本时——不管你给它起什么名字——解释器都会调用它"__main__"。这就是它如何跟踪哪个脚本是主文件,在外部调用另一个脚本后返回的脚本。(您可能会说“home”脚本。)从此“main”脚本调用的任何其他脚本都将其文件名指定为其__name__. 因此,该行if __name__ == "__main__" :是解释器的测试,以确定它是否正在它正在查看(解析)的脚本上运行,或者它是否正在临时查看另一个脚本。这使程序员可以灵活地让脚本在外部调用时表现不同。

To understand what's happening, focus first on the unindented lines and the order they appear in the scripts. Remember that function - or def- blocks don't do anything by themselves until they're called. What the interpreter might think if mumbled to itself:

要了解发生了什么,首先关注未缩进的行以及它们在脚本中的出现顺序。请记住,函数 - 或def- 块在被调用之前不会自己做任何事情。如果自言自语,口译员可能会怎么想:

  • Open xy.py.
  • Import and open file with the __name__ab.py.
  • Oh, a function. I'll remember that.
  • Ok, function a(); I just learned that. I guess I'll print now.
  • End of file; back to '__main__'!
  • Oh, a function. I'll remember that.
  • Another one.
  • Function x(); ok, printing 's'.
  • What's this? An ifstatement. Well, the condition has been met (the variable __name__has been set to '__main__'), so I'll print 'b function'.
  • 打开 xy.py。
  • 使用__name__ab.py导入并打开文件。
  • 哦,一个函数。我会记住的。
  • 好的,函数 a(); 我刚刚学会了。我想我现在就打印。
  • 文件结束;回'__main__'
  • 哦,一个函数。我会记住的。
  • 另一个。
  • 函数 x(); 好的,打印's'。
  • 这是什么?一个if声明。好吧,条件已满足(变量__name__已设置为'__main__'),因此我将打印“b 函数”。

However I don't think you're using it properly. There are probably exceptions, but the bottom two lines should be:

但是我认为你没有正确使用它。可能有例外,但最下面的两行应该是:

if __name__ == "__main__":
main()

... which means "If this is the 'main' or home script, execute the function called main(). That's why you'll see a def main():block up top, which contains the main flow of the script's functionality.

...这意味着“如果这是'主'或主脚本,则执行名为 的函数main()。这就是为什么您会def main():在顶部看到一个块,其中包含脚本功能的主要流程。

Why we implement this?

我们为什么要实施这个?

(Wow, I actually figured this part out while writing the above. This is the part I really struggled to understand, too, because I've never myself written a script with functions that I've called from other scripts.)

(哇,我实际上在编写上述内容时想通了这一部分。这也是我真正难以理解的部分,因为我自己从未编写过带有从其他脚本调用的函数的脚本。)

Remember what I said earlier about import statements? When you import a module it doesn't just 'recognize' it and wait for further instructions. It actually runs all the executable operations contained within the script. So, putting the meat of your script into the main()function effectively quarantines it, putting it in isolation so that it can't immediately run when imported by another script.

还记得我之前说过的关于 import 语句的内容吗?当您导入一个模块时,它不仅仅是“识别”它并等待进一步的指令。它实际上运行脚本中包含的所有可执行操作。因此,将脚本的主要内容放入main()函数中可以有效地隔离它,将其隔离,以便在被另一个脚本导入时无法立即运行。

Again, there will be exceptions, but common practice is that main()doesn't usually get called externally. So you may be wondering one more thing: if we're not calling main(), why are we calling the script at all? It's because many people structure their scripts with standalone functions that are built to be run by themselves. They're then later called somewhere else in the body of the script. Which brings me to this:

同样,会有例外,但通常的做法是main()通常不会从外部调用。所以你可能想知道一件事:如果我们不调用main(),我们为什么要调用脚本?这是因为许多人使用独立的函数来构建他们的脚本,这些函数是为自己运行而构建的。然后它们在脚本主体的其他地方被调用。这让我想到:

Our code is work without it also

我们的代码在没有它的情况下也能工作

Yes, you're right. These separate functions canbe called from an in-line script that's not contained inside a main()function. If you're accustomed (as I am, in my early learning stages of programming) to building in-line scripts that do exactly what you need, and you'll try to figure it out again if you ever need that operation again - well, you're not used to this kind of internal structure to your code, because it's more complicated to build, and it's not as intuitive to read. But that's a script that probably can't have its functions called externally, because if did it would start calculating and assigning variables. And chances are if you're trying to re-use a function, your new script is related closely enough to the old one that there could be conflicting variables.

你是对的。可以从不包含在main()函数内的内嵌脚本调用这些单独的函数。如果您习惯于(就像我一样,在我编程的早期学习阶段)构建完全符合您需要的内嵌脚本,并且如果您再次需要该操作,您将尝试再次弄清楚 - 好吧,你不习惯你的代码的这种内部结构,因为它构建起来更复杂,阅读起来也不那么直观。但这是一个可能无法在外部调用其函数的脚本,因为如果这样做,它将开始计算和分配变量。并且很有可能,如果您尝试重用某个函数,您的新脚本与旧脚本的关联度足够高,以至于可能存在变量冲突。

I should say as an aside, this threadcontains an answer by @kindall that finally helped me to understand - the Why, not the How. Unfortunately it's been marked as a duplicate of this one, which I think is a mistake. (I'm new to this board so can't flag it yet; if you agree with me, please flag it for further mod attention.)

顺便说一句,该线程包含@kindall 的答案,最终帮助我理解了-为什么,而不是如何。不幸的是,它被标记为this one的副本,我认为这是一个错误。(我是这个板子的新手,所以还不能标记它;如果你同意我的观点,请标记它以获得进一步的模组关注。)

回答by Shaurya Mittal

In simple words everything inside if __name__ == "__main__":is only run when the module is execute directly by python interpreter (ex: python module.py) OR if functions are called explicitly after importing.

简单来说,内部的所有if __name__ == "__main__":内容仅在模块由 python 解释器(例如:python module.py)直接执行或在导入后显式调用函数时运行。

EXAMPLE: testFile.py

示例:testFile.py

#this will always be executed even if this module is simply imported by other file or this module is the entry point
print "I will always run in any situation. Even when this module is 'just' imported"

if __name__ == "__main__":
    #this will be executed only when this module is the entry point eg. python testFile.py but not if this file is imported
    print "I will only run if this module (testFile.py) is executed directly by python interpreter"

app.py

应用程序

import testFile


pythontestFile.py

蟒蛇测试文件.py

Output: I will always run in any situation. Even when this module is 'just' imported

输出:在任何情况下我都会跑步。即使这个模块是“刚刚”导入的

I will only run if this module (testFile.py) is executed directly by python interpreter

只有当这个模块(testFile.py)被python解释器直接执行时,我才会运行



pythonapp.py

蟒蛇应用程序.py

Output: I will always run in any situation. Even when this module is 'just' imported

输出:在任何情况下我都会跑步。即使这个模块是“刚刚”导入的



if you want to learn about the internals of __name__variable: Check this What does if __name__ == "__main__": do?

如果你想了解__name__变量的内部结构:检查这个What do if __name__ == "__main__": do?

回答by seralouk

A really simple example to understand this statement is the following:

理解此语句的一个非常简单的示例如下:

Assume that we have the following python script named:'using_name.py':

假设我们有以下名为的 python 脚本:'using_name.py'



# Filename: using_name.py

if __name__ == '__main__':
    print 'This program is being run by itself'
else:
    print 'I am being imported from another module'


Now, try to do the following 2 things and see what happens:

现在,尝试做以下两件事,看看会发生什么:



1) Run directly the script

1)直接运行脚本

$ python using_name.py

Result

结果

This program is being run by itself


2) Import the script

2)导入脚本

$ python
import using_name

Result

结果

I am being imported from another module