title: Detect interactive shell in Python
body: <p>I want to be able to tell whether or not I'm in an interactive python shell. The definition I'm using is that the user is in the interactive python shell if it can enter commands (python is reading from stdin).</p>
  
  <p>Until now, I came up with the following script:</p>
  
  <pre><code>def detect_interactive():
  """Try to import interactive code. If it fails, we're either in_units
      no interactive ipython mode or in regular python mode"""
      import sys
  
      # IPython recognition is missing; test here if __IPYTHON__ exists, etc.
      if hasattr(sys, 'ps1'):
          # Running interactively
          is_interactive = True
      else:
          # Not interactive
          is_interactive = False
          if sys.flags.interactive:
              print("... but I'm in interactive postmortem mode.")
  
      # When running using IPython, it is always detected as being interactive!
      try:
          __IPYTHON__  # IPython specific code
          print('IPython detected')
      finally:
          print('interactive status:', is_interactive)
          return is_interactive
  </code></pre>
  
  <p>It works well for regular python. However, regardless of if I call this script using <code>ipython myscript.py</code> or if I run it from an IPython shell like <code>In [1]: %run detect.py</code>, I always have the is_interactive flag activated.</p>
  
  <p>So my question is: how can I detect the interactive mode of IPython?</p>