Detecting when a python script is being run interactively in ipython

I stumbled on the following and it seems to do the trick for me:

def in_ipython():
    try:
        return __IPYTHON__
    except NameError:
        return False

Docs say that sys.ps1 doesn't exist in noninteractive mode. Additionally, one can use sys.flags (for python 2.6+) to detect if we have used python -i <whatever>.

This scripts detects if we run interactively, non-interactively, and in post-mortem mode (which may be attributed to interactive mode if python interpreter is called using python -i implicitly and user thinks he landed into "interactive" console):

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys

# IPython recognition is missing; test here if __IPYTHON__ exists, etc.

if hasattr(sys, 'ps1'):
    print("Running interactively.")
else:
    print("Not running interactively...")
    if sys.flags.interactive:
        print("... but I'm in interactive postmortem mode.")

IPython support can be added as described by Mr Fooz.


When invoked interactively, python will run the script in $PYTHONSTARTUP, so you could simply have that environment variable invoke a script which sets a global