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?

- 1,022
- 1
- 8
- 21
4 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.

- 27,562
- 13
- 91
- 132
-
1For those not aware that Jupyter notebooks were developed from IPython notebooks, I'll point out that the addition of the second part works in Jupyter notebooks so that the pertinent code block won't be run when pasted into the cell of a notebook. Also, those considering this may be interested in the approach featured [here](https://stackoverflow.com/a/22424821/8508004). – Wayne Feb 15 '18 at 18:32
It sounds like you might just need the -x
switch:
In [1]: %edit
IPython will make a temporary file named: /tmp/ipython_edit_J8j9Wl.py
Editing... done. Executing edited code...
Name is main -- executing
Out[1]: "if __name__ == '__main__':\n print 'Name is main -- executing'\n"
In [2]: %edit -x /tmp/ipython_edit_J8j9Wl
Editing...
When you call %edit -x
the code is not executed after you exit your editor.

- 17,966
- 6
- 47
- 82
-
-
Thanks; this is useful, but it doesn't quite do what I want because I want IPython to load the functions/classes defined in the module, just not run the test code associated with the module. – ajd Apr 07 '14 at 23:16
-
No problem. I thought you might have some clarification like this. I would personally recommend @ffriend's answer in light of this. – Two-Bit Alchemist Apr 07 '14 at 23:18
IPython adds the function get_ipython()
to the globally available variables. So you can test, whether this function exist in globals()
to make your decision:
if __name__ == '__main__' and "get_ipython" not in dir():
print "I'm not loaded with IPython"
The above code just tests whether there is a global variable with name get_ipython
. To also test whether this variable is callable, you can do:
if __name__ == '__main__' and not callable(globals().get("get_ipython", None)):
print "I'm not loaded with IPython"

- 4,739
- 3
- 26
- 35
IPython automatically executes the code you write with the %edit
command. You can use %edit -x
to specify that you do NOT want to run the code you were just editing.
http://ipython.org/ipython-doc/stable/api/generated/IPython.core.magics.code.html

- 1,507
- 1
- 12
- 12