Checking to see if __name__ == '__main__'
is a common idiom to run some code when the file is being called directly, rather than through a module.
In the process of writing a custom command for Django's manage.py, I found myself needing to use code.InteractiveConsole
, which gives the effect to the user of a standard python shell. In some test code I was doing, I found that in the script I'm trying to execute, I get that __name__
is __console__
, which caused my code (dependent on __main__
) to not run.
I'm fairly certain that I have some things in my original implementation to change, but it got me wondering as to what different things __name__
could be. I couldn't find any documentation on the possible values, nor what they mean, so that's how I ended up here.
The __name__ variable (two underscores before and after) is a special Python variable. It gets its value depending on how we execute the containing script. Sometimes you write a script with functions that might be useful in other scripts as well. In Python, you can import that script as a module in another script.
The use of double underscore ( __ ) in front of a name (specifically a method name) is not a convention; it has a specific meaning to the interpreter. Python mangles these names and it is used to avoid name clashes with names defined by subclasses.
if __name__ == “main”: is used to execute some code only if the file was run directly, and not imported.
The value of __name__ attribute is set to “__main__” when module is run as main program. Otherwise, the value of __name__ is set to contain the name of the module. We use if __name__ == “__main__” block to prevent (certain) code from being run when the module is imported.
from the document of class code.InteractiveInterpreter([locals]):
The optional locals argument specifies the dictionary in which code will be executed; it defaults to a newly created dictionary with key '__name__'
set to '__console__'
and key '__doc__'
set to None
.
maybe u can turnning the locals argument, set __name__
with __main__
, or change the test clause from
if __name__ == '__main__'
to
if __name__ in set(["__main__", "__console__"])
Hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With