What does if __name__ == “__main__”: do?

匿名 (未验证) 提交于 2019-12-03 01:52:01

问题:

What does the if __name__ == "__main__": do?

# Threading example import time, thread  def myfunction(string, sleeptime, lock, *args):     while True:         lock.acquire()         time.sleep(sleeptime)         lock.release()         time.sleep(sleeptime)  if __name__ == "__main__":     lock = thread.allocate_lock()     thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))     thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock)) 

回答1:

When the Python interpreter reads a source file, it executes all of the code found in it.

Before executing the code, it will define a few special variables. For example, if the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value "__main__". If this file is being imported from another module, __name__ will be set to the module's name.

In the case of your script, let's assume that it's executing as the main function, e.g. you said something like

python threading_example.py 

on the command line. After setting up the special variables, it will execute the import statement and load those modules. It will then evaluate the def block, creating a function object and creating a variable called myfunction that points to the function object. It will then read the if statement and see that __name__ does equal "__main__", so it will execute the block shown there.

One reason for doing this is that sometimes you write a module (a .py file) where it can be executed directly. Alternatively, it can also be imported and used in another module. By doing the main check, you can have that code only execute when you want to run the module as a program and not have it execute when someone just wants to import your module and call your functions themselves.

See this page for some extra details.



回答2:

When your script is run by passing it as a command to the Python interpreter,

python myscript.py 

all of the code that is at indentation level 0 gets executed. Functions and classes that are defined are, well, defined, but none of their code gets run. Unlike other languages, there's no main() function that gets run automatically - the main() function is implicitly all the code at the top level.

In this case, the top-level code is an if block. __name__ is a built-in variable which evaluates to the name of the current module. However, if a module is being run directly (as in myscript.py above), then __name__ instead is set to the string "__main__". Thus, you can test whether your script is being run directly or being imported by something else by testing

if __name__ == "__main__":     ... 

If your script is being imported into another module, its various function and class definitions will be imported and its top-level code will be executed, but the code in the then-body of the if clause above won't get run as the condition is not met. As a basic example, consider the following two scripts:

# file one.py def func():     print("func() in one.py")  print("top-level in one.py")  if __name__ == "__main__":     print("one.py is being run directly") else:     print("one.py is being imported into another module") 
# file two.py import one  print("top-level in two.py") one.func()  if __name__ == "__main__":     print("two.py is being run directly") else:     print("two.py is being imported into another module") 

Now, if you invoke the interpreter as

python one.py 

The output will be

top-level in one.py one.py is being run directly 

If you run two.py instead:

python two.py 

You get

top-level in one.py one.py is being imported into another module top-level in two.py func() in one.py two.py is being run directly 

Thus, when module one gets loaded, its __name__ equals "one" instead of "__main__".



回答3:

The simplest explanation for the __name__ variable (imho) is the following:

Create the following files.

# a.py import b 

and

# b.py print "Hello World from %s!" % __name__  if __name__ == '__main__':     print "Hello World again from %s!" % __name__ 

Running them will get you this output:

$ python a.py Hello World from b! 

As you can see, when a module is imported, Python sets globals()['__name__'] in this module to the module's name.

$ python b.py Hello World from __main__! Hello World again from __main__! 

As you can see, when a file is executed, Python sets globals()['__name__'] in this file to "__main__".



回答4:

What does the if __name__ == "__main__": do?

The global variable, __name__, in the module that is the entry point to your program, is '__main__'.

So, code in this if block will only run if that module is the entry point to your program.


Why do we need this?

Developing and Testing Your Code

Say you're writing a Python script designed to be used as a module:

def do_important():     """This function does something very important""" 

You could test the module by adding this call of the function to the bottom:

do_important() 

and running it (on a command prompt) with something like:

~$ python important.py 

The Problem

However, if you want to import the module to another script:

import important 

On import, the do_important function would be called, so you'd probably comment out your call of the function at the bottom. And then you'll have to remember whether or not you've commented out your test function call. And this extra complexity would mean you're likely to forget, making your development process more troublesome.

A Better Way

The __name__ variable points to the namespace wherever the Python interpreter happens to be at the moment. Inside an imported module, it's the name of that module. But inside the primary module (or an interactive Python session, i.e. the interpreter's Read, Eval, Print Loop, or REPL) you are running everything from its "__main__".

So if you check before executing:

if __name__ == "__main__":     do_important() 

With the above, your code will only execute when you're running it as the primary module (or intentionally call it from another script).

An Even Better Way

There's a Pythonic way to improve on this, though.

What if we want to run this business process from outside the module? If we put the code we want to exercise as we develop and test in a function like this and then do our check for '__main__' immediately after:

def main():     """business logic for when running this module as the primary one!"""     setup()     foo = do_important()     bar = do_even_more_important(foo)     for baz in bar:         do_super_important(baz)     teardown()  # Here's our payoff idiom! if __name__ == '__main__':     main() 

We now have a final function for the end of our module that will run if we run the module as the primary module. It will allow the module and its functions and classes to be imported into other scripts without running the main function, and will also allow the module (and its functions and classes) to be called when running from a different '__main__' module, i.e.

import important important.main() 

This idiom can also be found in the Python documentation in an explanation of the __main__ module. That text states:

This module represents the (otherwise anonymous) scope in which the interpreter’s main program executes ― commands read either from standard input, from a script file, or from an interactive prompt. It is this environment in which the idiomatic “conditional script” stanza causes a script to run:

if __name__ == '__main__':     main() 


回答5:

if __name__ == "__main__" is the part that runs when the script is run from (say) the command line using a command like python myscript.py.



回答6:

What does if __name__ == "__main__": do?

__name__ is a global variable (in Python, global actually means on the module level) that exists in all namespaces. It is typically the module's name (as a str type).

As the only special case, however, in whatever Python process you run, as in mycode.py:

python mycode.py 

the otherwise anonymous global namespace is assigned the value of '__main__' to its __name__.

Thus, including the final lines

if __name__ == '__main__':     main() 
  • at the end of your mycode.py script,
  • when it is the primary, entry-point module that is run by a Python process,

will cause your script's uniquely defined main function to run.

Another benefit of using this construct: you can also import your code as a module in another script and then run the main function if and when your program decides:

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


回答7:

When there are certain statements in our module (M.py), we want to be executed when it 'll be running as main (not imported), in that case we can place those statements (test-cases, print statements) under this if block. As by default (when module running as main, not imported) the __name__ variable is set to "__main__", and when it'll be imported the __name__ variable 'll get a different value, most probably the name of the module ('M'). This is helpful in running different variants of a modules together, and seperating their specific input & output statements and also if any test-cases.

In short , use this 'if __name__ == "main" ' block to prevent (certain) code from being run when the module is imported.



回答8:

Lots of different takes here on the mechanics of the code in question, the "How", but for me none of it made sense until I understood the "Why". This should be especially helpful for new programmers.

Take file "ab.py":

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

and a second file "xy.py":

import ab def main():     print('main function: this is where the action is') def x():      print ('peripheral task: might be useful in other projects') x() if __name__ == "__main__":     main() 

What is this code actually doing?

When you execute xy.py, you import ab. The import statement runs the module immediately on import, so ab's operations get executed before the remainder of xy's. Once finished with ab, it continues with 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__", making it the master or 'home' script that gets returned to after running an external script. Any other script that's called from this "__main__" script is assigned its filename as its __name__ (e.g., __name__ == "ab.py"). Hence, the line if __name__ == "__main__": is the interpreter's test to determine if it's interpreting/parsing the 'home' script that was initially executed, or if it's temporarily peeking into another (external) script. This gives the programmer flexibility to have the script behave differently if it's executed directly vs. called externally.

Let's step through the above code to understand what's happening, focusing 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 say if mumbled to itself:

  • Open xy.py as the 'home' file; call it "__main__" in the __name__ variable.
  • Import and open file with the __name__ == "ab.py".
  • Oh, a function. I'll remember that.
  • Ok, function a(); I just learned that. Printing 'A function in ab file'.
  • End of file; back to "__main__"!
  • Oh, a function. I'll remember that.
  • Another one.
  • Function x(); ok, printing 'peripheral task: might be useful in other projects'.
  • What's this? An if statement. Well, the condition has been met (the variable __name__ has been set to "__main__"), so I'll enter the main() function and print 'main function: this is where the action is'.

The bottom two lines mean: "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.

Why implement this?

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 won't immediately run when imported by another script.

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:

But the code works without it

Yes, that's right. These separate functions can be 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 it 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.

In splitting out independent functions, you gain the ability to re-use your previous work by calling them into another script. For example, "example.py" might import "xy.py" and call x(), making use of the 'x' function from "xy.py". (Maybe it's capitalizing the 3rd word of a given text string; creating a numpy array from a list of numbers and squaring them; or detrending a 3D surface. The possibilities are limitless.)

I should say as an aside, this thread contains 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.



回答9:

Let's look at the answer in a more abstract way:

Suppose we have this code in x.py:

...  if __name__ == '__main__':      ... 

Blocks A and B are run when we are running "x.py".

But just block A (and not B) is run when we are running another module, "y.py" for example, in which x.y is imported and the code is run from there (like when a function in "x.py" is called from y.py).



回答10:

When you run Python interactively the local __name__ variable is assigned a value of __main__. Likewise, when you execute a Python module from the command line, rather than importing it into another module, its __name__ attribute is assigned a value of __main__, rather than the actual name of the module. In this way, modules can look at their own __name__ value to determine for themselves how they are being used, whether as support for another program or as the main application executed from the command line. Thus, the following idiom is quite common in Python modules:

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. 


回答11:

Put Simply __name__ is a variable defined for each script, that defines whether the script is being run as the main module or it is being run as an imported module.

So if we have two scripts;

#script1.py print "Script 1's name: {}".format(__name__) 

and ;

#script2.py import script1 print "Script 2's name: {}".format(__name__) 

The output from executing script1 is;

Script 1's name: __main__ 

and the output from executing script2 is;

Script1's name is script1  Script 2's name: __main__ 

As you can see; __name__ tells us which code is the 'main' module. This is great because you can just write code and not have to worry about structural issues like in C/C++, where, if a file does not implement a 'main' function then it cannot be compiled as an executable and if it does, it cannot then be used as a library.

Say you write a python script that does something great and you implement a boatload of functions that are useful for other purposes, if I want to use them I can just import your script and use them without executing your program(given that your code only executes within the if __name__ == "__main__": context). Whereas in C/C++ you would have to portion out those pieces into a seperate module that then includes the file. Picture the situation below;

The arrows are import links. For three modules each trying to include the previous modules code there are six files(nine, counting the implementation files) and five links , this makes it difficult to include other code into a c project unless it is compiled specifically as a library. Now picture it for python;

You write a module, If someone wants to utilize your code they just import it and the __name__ variable can help to seperate the executable portion of the program from the library part.



回答12:

if __name__ == "__main__":     main() 

Checks if the __name__ attribute of the python script is "__main__". In other words, if the program itself is executed, the attribute will be __main__, so the program will be executed (in this case the main() function).

However, if your python script is used by a module, any code outside of the if statement will be executed, so if \__name__ == "\__main__" is used just to check if the program is used as a module or not, and therefore decides whether to run the code.



回答13:

It is a special for when a Python file is called from the command line. This is typically used to call a "main()" function or execute other appropriate startup code, like commandline arguments handling for instance.

It could be written in several ways, another is:

def main():     dosomething()   __name__ == '__main__' and main() 

I am not saying you should use this in production code, but it serves to illustrate that there is nothing "magical" about if __name__ == '__main__'. It is a (great!) convention for invoking a main function in Python files.



回答14:

There are a number of variables that the system (Python interpreter) provides for source files (modules). You can get their values anytime you want, so, let us focus on the __name__ variable/attribute:

When Python loads a source code file, it executes all of the code found in it. (Note that it doesn't call all of the methods and functions defined in the file, but it does define them.)

Before the interpreter executes the source code file though, it defines a few special variables for that file; __name__ is one of those special variables that Python automatically defines for each source code file.

If Python is loading this source code file as the main program (i.e. the file you run), then it sets the special __name__ variable for this file to have a value "__main__".

If this is being imported from another module, __name__ will be set to that module's name.

So, in your example in part:

if __name__ == "__main__":    lock = thread.allocate_lock()    thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))    thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock)) 

means that the code block:

lock = thread.allocate_lock() thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock)) 

will be executed only when you run the module directly; the code block will not execute if another module is calling/importing it because the value of __name__ will not equal to "main" in that particular instance.

Hope this helps out.



回答15:

if __name__ == "__main__": is basically Top-level script environment, it specifies the interpreter that ('I have the highest priority to be executed first').

'__main__' is the name of the scope in which top-level code executes. A module’s name is set equal to 'main' when read from standard input, a script, or from an interactive prompt.

if __name__ == "__main__":     # execute only if run as a script     main() 


回答16:

I think it's best to break the answer in depth and in simple words:

__name__ : Every module in Python has a special attribute called __name__. It is a built-in variable that returns the name of the module.

__main__ : Like other programming languages, Python too has an execution entry point i.e. main. 'main' is the name of the scope in which top-level code executes. Basically you have two ways of using a Python module: Run it directly as a script, or import it. When a module is run as a script, its __name__ is set to __main__.

Thus,the value of __name__ attribute is set to __main__ when the module is run as main program. Otherwise the value of __name__ is set to contain the name of the module.



回答17:

You can make the file usable as a script as well as an importable module.

fibo.py (a module named fibo)

# Other modules can IMPORT this MODULE to use the function fib def fib(n):    # write Fibonacci series up to n     a, b = 0, 1     while b 

Reference: https://docs.python.org/3.5/tutorial/modules.html



回答18:

print __name__ 

output for the above is __main__

if __name == "__main__":   print "direct method" 

the above statement is gets true and print direct method suppose if they imported this class in other class it doesnt print direct method .because while importing it will set __name__ == "firstmodel name"



回答19:

The reason for

if __name__ == "__main__":     main() 

is primarily to avoid the import lock problems that would arise from having code directly imported.

A side-effect is that you automatically sign on to a methodology that supports multiple entry points.



回答20:

create a file a.py

print(__name__) #it will print out __main__ 

__name__ is always equal to __main__ whenever that file is run directly showing that this is the main file.

create another file b.py in the same directory

import a   #prints a 

run it. it will print a i.e name of the file which is imported.

so, to show two different behavior of the same file, this is a commonly used trick.

# code to be run when imported into another python file  if __name__ == '__main__':     #code to be run only when run directly 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!