Chinmay Kanchi Chinmay Kanchi - 1 month ago 8
Python Question

Tell if Python is in interactive mode

In a Python script, is there any way to tell if the interpreter is in interactive mode? This would be useful so that, for instance, when you run an interactive Python session and import a module, slightly different code is executed (for example, logging is turned off).

I've looked at tell whether python is in -i mode and tried the code there, however, that function only returns true if Python has been invoked with the -i flag and not when the command used to invoke interactive mode is

python
with no arguments.

What I mean is something like this:

if __name__=="__main__":
#do stuff
elif __pythonIsInteractive__:
#do other stuff
else:
exit()

Answer

__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.