views:

158

answers:

3

In a python script, is there any way to tell if the interpreter is in interactive mode? This would be useful, for instance, when you run an interactive python session and import a module, slightly different code is executed (for example, log file writing is turned off, or a figure won't be produced, so you can interactively test your program while still executing startup code so variables etc. are declared)

I've looked at http://stackoverflow.com/questions/640389/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()
+6  A: 

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

Ignacio Vazquez-Abrams
That works, thanks...
Chinmay Kanchi
This is also the case in, for example, py2exe executables.
fmark
+5  A: 

sys.ps1and sys.ps2 are only defined in interactive mode (http://docs.python.org/library/sys.html#sys.ps1).

ChristopheD
Also works. Thanks.
Chinmay Kanchi
+2  A: 

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 with if sys.argv[0] == ''. This also returns true if started with python -i, but according to the docs, they're functionally the same.

echoback
This works too. Guess there are a ton of ways to do this :)
Chinmay Kanchi
Uh oh. Direct violation of the Zen of Python, then :)
Tim Pietzcker
Heh... Though I think @echoback's version is the only obvious(ish) one. I didn't accept this simply because in C et al., it is theoretically possible that `argv[0]` is `NULL` or an empty string and I don't really feel like debugging any potential errors caused by that...
Chinmay Kanchi