Executing an Interactive Python Shell (REPL) for a Script

Sometimes you want to be able to get a REPL (Read Eval Print Loop) shell when running a Python script. This can help you interactively test manipulations of data and functions with your code, without having to amend your script, write the file, and then re-run it.

For this, you have two choices:

You can either run Python interactively, and import the file:

$ python
Python 3.6.4 (default, Jan  5 2018, 02:35:40)
[GCC 7.2.1 20171224] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import script
>>>

Alternatively, you can use python -i:

$ python -i script.py

For instance, given the Python source file script.py:

def output(arg):
    print(arg)


output('hi')

Running python -i:

$ python -i script.py
hi
>>> output(1)
1
>>> output({ 'a': 'b' })
{'a': 'b'}
>>>

As you can see, we can now use the output function from the REPL. It also prints hi, as that code is executing due to it being within the main body of the code.

*****

Written by Jamie Tanna on 08 April 2018, and last updated on 30 April 2018.

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under Apache License 2.0.

Tags

Categories