Detecting -i in a script

Christian Heimes lists at
Tue Apr 14 04:18:54 CEST 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


More information about the Python-list mailing list