Tell if Python is in interactive mode
sys.ps1
and sys.ps2
are only defined in interactive mode.
__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
.
Use sys.flags
:
if sys.flags.interactive:
#interactive
else:
#not interactive
I compared all the methods I found and made a table of results. The best one seems to be this:
hasattr(sys, 'ps1')
If anyone has other scenarios that might differ, comment and I'll add it