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 equivalent of -i. But apparently it doesn't work the same way.
Works:
$ PYTHONINSPECT=1 python -c 'import os; print os.environ["PYTHONINSPECT"]'
Doesn't work:
$ python -i -c 'import os; print os.environ["PYTHONINSPECT"]'
The reason I ask is because I have a script that calls sys.exit(-1) if certain conditions fail. This is good, but sometimes I want to manually debug it using -i. I suppose I can just learn to use "PYTHONINSPECT=1 python" instead of "python -i", but it would be nice if there were a universal way of doing this.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With