I have Python scripts that use the if __name__ == '__main__'
trick to have some code only run when the script is called as a script and not when it is loaded into the interactive interpreter. However, when I edit these scripts from IPython using the %edit
command, IPython apparently sets __name__
to '__main__'
and so the code gets run every time I exit the editing session. Is there a good way to make this code not run when the module is edited from IPython?
if __name__ == "__main__" in ActionWe use the if-statement to run blocks of code only if our program is the main program executed. This allows our program to be executable by itself, but friendly to other Python modules who may want to import some functionality without having to run the code.
We can use an if __name__ == "__main__" block to allow or prevent parts of code from being run when the modules are imported. When the Python interpreter reads a file, the __name__ variable is set as __main__ if the module being run, or as the module's name if it is imported.
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.
Python files can act as either reusable modules, or as standalone programs. if __name__ == “main”: is used to execute some code only if the file was run directly, and not imported.
When working from within Emacs (which I assume is close to what you get with %edit
), I usually use this trick:
if __name__ == '__main__' and '__file__' in globals(): # do what you need
For obvious reasons, __file__
is defined only for import
'ed modules, and not for interactive shell.
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