Executing an Interactive Python Shell (REPL) for a Script

Featured image for sharing metadata for article

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's profile image 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.

#command-line #python #blogumentation #tools #howto.

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

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

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.