Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if __name__ == '__main__' in IPython

Tags:

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?

like image 247
ajd Avatar asked Apr 07 '14 21:04

ajd


People also ask

What is if name == Main in Python?

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.

What is if __ name __ ==?

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.

What does __ main __ mean in Python?

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.

What is the use of name == Main?

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.


1 Answers

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.

like image 52
ffriend Avatar answered Nov 04 '22 11:11

ffriend