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()
Use
sys.flags
:__main__.__file__
doesn't exist in the interactive interpreter:This also goes for code run via
python -c
, but notpython -m
.From TFM: If no interface option is given, -i is implied, sys.argv[0] is an empty string ("") and the current directory will be added to the start of sys.path.
If the user invoked the interpreter with
python
and no arguments, as you mentioned, you could test this withif sys.argv[0] == ''
. This also returns true if started withpython -i
, but according to the docs, they're functionally the same.Here's something that would work. Put the following code snippet in a file, and assign the path to that file to the
PYTHONSTARTUP
environment variable.And then you can use
http://docs.python.org/tutorial/interpreter.html#the-interactive-startup-file
The following works both with and without the -i switch:
sys.ps1
andsys.ps2
are only defined in interactive mode.