Detecting -i in a script

Christian Heimes lists at cheimes.de
Mon Apr 13 22:18:54 EDT 2009


Marek Szuba wrote:
> Is there any way of detecting in a script whether the interpreter
> session running it has been launched with the -i option? My Google fu
> has failed me on this subject... Thanks in advance.

There is no direct way to detect the interactive flag. However sys.ps1
and sys.ps2 are not set unless the interpreter runs in interactive mode.

import sys
isinteractive = hasattr(sys, "ps1")

The trick doesn't work if you want to get the flag's state before the
interactive interpreter starts.

You could query the internal state of the Py_InteractiveFlag flag with
ctypes. sys.flags does it, too.

import ctypes
ctypes.cast(ctypes.pythonapi.Py_InteractiveFlag,
ctypes.POINTER(ctypes.c_int)).contents.value

Christian




More information about the Python-list mailing list