tell whether python is in -i mode

前端 未结 3 1994
孤独总比滥情好
孤独总比滥情好 2020-12-06 19:41

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

3条回答
  •  太阳男子
    2020-12-06 20:02

    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.

提交回复
热议问题