Difference between “inspect” and “interactive” command line flags in Python

后端 未结 2 466
庸人自扰
庸人自扰 2021-01-12 18:52

What is the difference between \"inspect\" and \"interactive\" flags? The sys.flags function prints both of them.

How can they both have \"-i\" flag according to the

相关标签:
2条回答
  • 2021-01-12 19:20

    man python says about the -i flag:

    When a script is passed as first argument or the -c option is used, enter interactive mode after executing the script or the command. It does not read the $PYTHONSTARTUP file. This can be useful to inspect global variables or a stack trace when a script raises an exception.

    Hence -i allows inspection of a script in interactive mode. -i implies both of these things. You can be interactive without inspecting (namely by just calling python, without arguments), but not vice versa.

    0 讨论(0)
  • 2021-01-12 19:36

    According to pythonrun.c corresponding Py_InspectFlag and Py_InteractiveFlag are used as follows:

    int Py_InspectFlag; /* Needed to determine whether to exit at SystemError */
    /* snip */
    static void
    handle_system_exit(void)
    {
        PyObject *exception, *value, *tb;
        int exitcode = 0;
    
        if (Py_InspectFlag)
            /* Don't exit if -i flag was given. This flag is set to 0
             * when entering interactive mode for inspecting. */
            return;
        /* snip */
    }
    

    Python doesn't exit on SystemExit if "inspect" flag is true.

    int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
    /* snip */
    /*
     * The file descriptor fd is considered ``interactive'' if either
     *   a) isatty(fd) is TRUE, or
     *   b) the -i flag was given, and the filename associated with
     *      the descriptor is NULL or "<stdin>" or "???".
     */
    int
    Py_FdIsInteractive(FILE *fp, const char *filename)
    {
        if (isatty((int)fileno(fp)))
            return 1;
        if (!Py_InteractiveFlag)
            return 0;
        return (filename == NULL) ||
               (strcmp(filename, "<stdin>") == 0) ||
               (strcmp(filename, "???") == 0);
    }
    

    If "interactive" flag is false and current input is not associated with a terminal then python doesn't bother entering "interactive" mode (unbuffering stdout, printing version, showing prompt, etc).

    -i option turns on both flags. "inspect" flag is also on if PYTHONINSPECT environment variable is not empty (see main.c).

    Basically it means if you set PYTHONINSPECT variable and run your module then python doesn't exit on SystemExit (e.g., at the end of the script) and shows you an interactive prompt instead of (allowing you to inspect your module state (thus "inspect" name for the flag)).

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