2

i.e. can you do something like:

if we_are_in_ipython:
    do_some_ipython_specific_stuff()

normal_python_stuff()

I guess what I'm trying to do is very loosely along the lines of #if DEBUG in C# (i.e. using ipython as a debugging tool and command line python to run the code without the debugging stuff in there).

tdc
  • 8,219
  • 11
  • 41
  • 63
  • 1
    Isn't IPython mainly intended for interactive use? Then you probably know that you are using it. –  Feb 01 '12 at 09:35
  • 3
    Looks like a duplicate of http://stackoverflow.com/q/5376837/407651 – mzjn Feb 01 '12 at 09:36
  • Ok maybe a concrete example will help. If I'm using ipython, I put the line `from IPython.Debugger import Tracer; debug_here = Tracer()` at the top of my file and then `debug_here()` statements throughout the file. However the first line generates an error from the command line (`AttributeError: 'function' object has no attribute 'colors'`) and additionally I wouldn't want the `debug_here()` statements to be called anyway – tdc Feb 01 '12 at 09:38
  • 1
    Duplicate of http://stackoverflow.com/questions/5376837/how-can-i-do-an-if-run-from-ipython-test-in-python – atp Feb 01 '12 at 09:38
  • @user647772 If you want to write a library that supports additional functionality when in IPython/Jupyter, you need a way to case that off. – Kyle Kelley Oct 19 '16 at 19:22

3 Answers3

4

Check for the __IPYTHON__ variable:

def is_ipython():
    try:
        __IPYTHON__ 
        return True
    except: 
        return False
Kyle Kelley
  • 13,804
  • 8
  • 49
  • 78
avasal
  • 14,350
  • 4
  • 31
  • 47
  • What if I have `__IPYTHON__` as a variable – Jakob Bowyer Feb 01 '12 at 11:03
  • 3
    Python uses `__name__` with leading and trailing underscores for special system functions with pre-defined behaviour. It would be a bad nomenclature from programmers part is what i feel. – avasal Feb 01 '12 at 11:19
1

As explained on the duplicate, you can use the try/except method, or

if '__IP' in globals():
    # stuff for ipython
    pass

Or check the __IPYTHON__ in builtin:

import __builtin__
if hasattr(__builtin__, '__IPYTHON__'):
    # stuff for ipython
    pass
Community
  • 1
  • 1
tito
  • 12,990
  • 1
  • 55
  • 75
1

Yes.

if 'get_ipython' in dir():
    """
       when ipython is fired lot of variables like _oh, etc are used.
       There are so many ways to find current python interpreter is ipython.
       get_ipython is easiest is most appealing for readers to understand.
    """
    do_some_thing_
else:
    don_sonething_else
Kracekumar
  • 19,457
  • 10
  • 47
  • 56