How can you tell whether python has been started with the -i flag?
According to the docs, you can check the PYTHONINSPECT variable in os.environ, which is the eq
I took a look at the source, and although the variable set when -i is provided is stored in Py_InteractiveFlag, it doesn't look like it gets exposed to python.
However, if you don't mind getting your hands a bit dirty with some low-level ctypes inspecting, I think you can get at the value by:
import ctypes, os
def interactive_inspect_mode():
flagPtr = ctypes.cast(ctypes.pythonapi.Py_InteractiveFlag,
ctypes.POINTER(ctypes.c_int))
return flagPtr.contents.value > 0 or bool(os.environ.get("PYTHONINSPECT",False))
[Edit] fix typo and also check PYTHONINSPECT (which doesn't set the variable), as pointed out in comments.
The answer from the link @Jweede provided is imprecise. It should be:
import os
os.environ['PYTHONINSPECT'] = '1'
Just another variant of @Brian's answer:
import os
from ctypes import POINTER, c_int, cast, pythonapi
def in_interactive_inspect_mode():
"""Whether '-i' option is present or PYTHONINSPECT is not empty."""
if os.environ.get('PYTHONINSPECT'): return True
iflag_ptr = cast(pythonapi.Py_InteractiveFlag, POINTER(c_int))
#NOTE: in Python 2.6+ ctypes.pythonapi.Py_InspectFlag > 0
# when PYTHONINSPECT set or '-i' is present
return iflag_ptr.contents.value != 0
See the Python's main.c.
This specifies how to programatically switch your script to interactive mode.