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


Running python -i:

$ python -i script.py
>>> output(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 , and last updated on .

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 the Apache License 2.0.

Related Posts

Other posts you may be interested in:

Interactions with this post

Interactions with this post

This post has had 0 WebMention interactions, as of Thu, 23 May 2019 13:53:35 +0100.

Have you written a response to this post? Let me know the URL: