Search code examples
macospython-3.xread-eval-print-loop

What exactly happens when I run python3 -i file.py


Lets say test.py has the contents

i_am_a_variable = 1
i_am_also_a_var = 2

while True:
    input('> ')

Then, while in the same directory as test.py, I run python3. Now then, in the REPL, I execute from test import *. Since the Python 3 REPL has auto-completion, variables are actually also auto-completed in this infinite input loop. That is, when I run

$ python3
>>> from test import *
> i_am_a|

(| represents my cursor) If I press tab, as if my cursor is at the end of the line i_am_a, it will auto-complete to i_am_a_variable.

Now, if I run python3 -i test.py, this behavior does not occur. That is, the REPL will not auto-complete. So what exactly occurs when I run python3 -i test.py. Does test.py just run and then globals gets copied over to the REPL?

This was tested on macOS, In case auto-completion is not available on other python distributions. Thanks.


Solution

  • Python initializes autocompletion when interactive mode is entered. (If you want the details, it calls sys.__interactivehook__, and one of the things the default __interactivehook__ does is import rlcompleter and configure TAB to trigger completion.)

    When you launch Python in interactive mode and then run from test import * interactively, Python turns on autocompletion before it hits the input loop. Autocompletion isn't really intended to affect input, but it does anyway.

    When you run test.py with python3 -i, Python doesn't enter interactive mode. It plans to enter interactive mode when test.py finishes, and it plans to run sys.__interactivehook__ and turn on autocompletion when that happens, but the input loop happens before it reaches that point.