tell whether python is in -i mode

前端 未结 3 1983
孤独总比滥情好
孤独总比滥情好 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.

    0 讨论(0)
  • 2020-12-06 20:18

    How to set inspect mode programmatically

    The answer from the link @Jweede provided is imprecise. It should be:

    import os
    os.environ['PYTHONINSPECT'] = '1'
    

    How to retrieve whether interactive/inspect flags are set

    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.

    0 讨论(0)
  • 2020-12-06 20:21

    This specifies how to programatically switch your script to interactive mode.

    0 讨论(0)
提交回复
热议问题