Tell if Python is in interactive mode
__main__.__file__
doesn't exist in the interactive interpreter:
import __main__ as mainprint hasattr(main, '__file__')
This also goes for code run via python -c
, but not python -m
.
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