Tell if Python is in interactive mode

Solution 1:

__main__.__file__ doesn't exist in the interactive interpreter:

import __main__ as main
print hasattr(main, '__file__')

This also goes for code run via python -c, but not python -m.

Solution 2:

sys.ps1 and sys.ps2 are only defined in interactive mode.