Given a simple script like:
#!/usr/bin/env python3
if __name__ == "__main__":
print("Hello World")
How can I load that into the interactive interpreter without executing the if __name__ == "__main__":
block? By default it gets executed:
$ python3 -i simple-script.py
Hello World
>>> █
if __name__ == “main”: is used to execute some code only if the file was run directly, and not imported.
The Reason Behind if __name__ == '__main__' in Python You might have seen this one before: the syntax which often gets ignored because it doesn't seem to hinder the execution of your code. It may not seem necessary, but that's only if you're working with a single Python file.
__main__ — Top-level code environment. In Python, the special name __main__ is used for two important constructs: the name of the top-level environment of the program, which can be checked using the __name__ == '__main__' expression; and. the __main__.py file in Python packages.
A widely used way to run Python code is through an interactive session. To start a Python interactive session, just open a command-line or terminal and then type in python , or python3 depending on your Python installation, and then hit Enter .
Don't pass it as an argument, import it into the interpreter.
$ python3
>>> import simple_script
>>>
From within the script itself, you can detect if -i
was passed by looking at the sys.flags.inspect
flag:
import sys
if __name__ == '__main__':
# code run with or without -i
if not sys.flags.inspect:
# code not run with -i
In addition to @DanielRoseman's answer, if you use the IPython or jupyter interpreter, you could use the %run
magic with the -n
flag:
-n __name__ is NOT set to ‘__main__’, but to the running file’s name without extension (as python does under import). This allows running scripts and reloading the definitions in them without calling code protected by an if __name__ == "__main__" clause.
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