Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip `if __name__ == "__main__"` in interactive mode?

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
>>> █
like image 788
Grumbel Avatar asked May 07 '15 18:05

Grumbel


People also ask

What is the meaning of if __ name __ == '__ Main__?

if __name__ == “main”: is used to execute some code only if the file was run directly, and not imported.

Is if name == Main necessary?

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.

What is if __ main __ in Python?

__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.

How do I run an interactive mode script in Python?

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 .


3 Answers

Don't pass it as an argument, import it into the interpreter.

$ python3
>>> import simple_script
>>>
like image 64
Daniel Roseman Avatar answered Oct 23 '22 01:10

Daniel Roseman


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
like image 33
nneonneo Avatar answered Oct 23 '22 00:10

nneonneo


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.

like image 21
PlasmaBinturong Avatar answered Oct 22 '22 23:10

PlasmaBinturong