Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "inspect" and "interactive" command line flags in Python

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 documentation of sys.flags?

How can I set them separately? If I use "python -i", both of them will be set to 1.

Related:

  • tell whether python is in -i mode
like image 860
hcs42 Avatar asked Jul 17 '09 20:07

hcs42


1 Answers

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)).

like image 61
jfs Avatar answered Sep 18 '22 19:09

jfs