How To Execute a File Within the Python Interpreter

No matter the stage of your Python development career,  you probably already appreciate the importance of running and testing your code. This is the only way to ensure it works as planned and does what you need it to do. But how do you actually run scripts and code? This article will give you a brief overview of the various methods available.

What is a Python Interpreter

To start with let’s just clarify what the Python Interpreter actually is. I believe the simplest description is the best – it interprets the Python code you write and makes it understandable to the computer you want to run the code on. 

Running Python Scripts

To start with, let’s create a test script. I will use the script below which I will save in a file called test_script.py  in the directory C:\Users\Rikesh

print('Hello, my name is Rikesh and I am a Python developer')

All the methods outlined below look at different ways of executing this one simple line of code, using a Windows 10 machine running Python v.3.8.6

Method 1: Using the Command Line

For me, this is the simplest way of running your scripts.  Whilst there may be variations in the specific syntax, the principle is the same – invoke the Python interpreter and then tell it the name of the script you want to run. 

To walk through how this is done:

Open a command line prompt and navigate to the same working directory as your script:

C:\Users\Rikesh>

Invoke the  Python Interpreter by typing it’s name. This is generally done by simply typing python but if you have older versions of Python installed and want to specify version 3.x.x you can use python3. As I only have one version installed, even though it is version 3, I can just use the default python. Finally we just need to point the Python interpreter to our script by specifying the file name and press ‘Enter’

C:\Users\Rikesh>python test_script.py 
Hello, my name is Rikesh and I am a Python developer

Using the Command Line in Windows

If you are running Windows, you have a few more options for running your scripts from the command line.

py is the Python launcher utility that comes with Python installations on Windows.  It will, by default, use the latest Python version that is installed on your machine. So, to run Python scripts  on a Windows machine we can also use: 

C:\Users\Rikesh>py test_script.py 
Hello, my name is Rikesh and I am a Python developer 

Finally, the most recent versions of Windows will know you are trying to run a Python script from the file association .py so there is no need to invoke the Python Interpreter at all! 

C:\Users\Rikesh>test_script.py 
Hello, my name is Rikesh and I am a Python developer

Method 2: Running Scripts Interactively Using Import

There may be times when it is impractical to run scripts or code through the command line, so we can also run them directly through the Python interactive shell. To start with, we need to open a Python interactive shell by typing python in our command line. Again, we need to make sure we are in the same working directory as our script.  

C:\Users\Rikesh>python
>>>

We know this has worked when we see the ‘>>>’ which shows us we are in the Python shell. 

If you have had any experience using Python, you will probably be familiar with the import module when importing  scripts and libraries for later use.  The import module also executes any code as part of this process as well, although this is only seen when visible output is being generated. Given our script is essentially a print statement,  we can therefore use it to our advantage: 

>>>import test_script
Hello, my name is Rikesh and I am a Python developer 

Be warned however that you can only run this command once per Python session. If you try to run the same command again in the same session it will not execute the file as the import operation has already been run:

>>>import test_script
>>> 

Method 3: Running Scripts Interactively Using the Python Standard Library: Importlib

The Python Standard Library has a number of modules that can also run Python scripts.  Let’s look at two of the key ones: importlib and runpy

The import_module of importlib works in the same way as the standard import module described previously. 

>>>import importlib
>>>importlib.import_module('test_script') 
Hello, my name is Rikesh and I am a Python Developer
<module ‘test_script’ from ‘C:\\Users\\Rikesh\\test_script.py’>

Whilst this has been successful as with the previous import module, the script can only be executed once as we are importing the script as a module. So if we try to run the code again, the script is not executed: 

>>>importlib.import_module('test_script') 
<module ‘test_script’ from ‘C:\\Users\\Rikesh\\test_script.py’>

To run again you have to use the importlib.reload() function which, as the name suggests, reloads the function. But take note that the argument for the .reload() function has to be the module name, not a string i.e test_script not  ‘test_script‘

>>>import importlib
>>>importlib.reload(test_script) 
Hello, my name is Rikesh and I am a Python Developer
<module ‘test_script’ from ‘C:\\Users\\Rikesh\\test_script.py’>

Method 4: Running Scripts Interactively Using the Python Standard Library: Runpy 

The runpy module is used to locate and run Python modules without importing them first.

Within this module there are two functions that can help us execute our file : runpy.run_module() and runpy.run_path(). Whilst I have included the code below, it should be noted that in addition to executing the script, it also returns the entire globals dictionary of the module. When I first tried this, my initial reaction was that there was an error as the print statement output was lost in the dictionary output.  

>>>import runpy
>>>runpy.run_module(mod_name='test_script') 
Hello, my name is Rikesh and I am a Python Developer
{'__name__': 'test_script',
    …
'_': None}}

As you can see it takes the string of the script without the .py extension i.e ‘test_script’ as the first argument. 

Alternatively you can use run_path() which allows you to run a file based on location: 

>>>import runpy
>>>runpy.run_path(’test_script.py’) 
Hello, my name is Rikesh and I am a Python Developer
{'__name__': '<run_path>',
    …
'_': None}}

Whilst the runpy module does execute the file, given the constraints with printing the dictionary it’s use is limited. The main use of the runpy module in Python is to implement the -m command rather than running scripts directly. 

Method 5: The exec() Function

This is a built-in Python function that dynamically executes the Python script/code and can be used as follows: 

>>>exec(open('test_script.py').read())
Hello, my name is Rikesh and I am a Python developer 

When I initially saw this function, it appeared to be the most logical of all the interactive examples. As the command line indicates, we are opening the file (‘test_script.py’), reading it and then using the exec() function to execute. No dictionaries are printed and you can use this function multiple times with no issues. In my opinion, this is the simplest and most effective way of running Python scripts interactively.  

However, whilst it appears to work well and is recommended on sites such as stackoverflow, many feel it is the method of ‘last resort’. They consider it to be slow, unpredictable and can be open to security issues. Caution is therefore recommended in using this function.

Summary

As you can see, there are various ways of executing files within the Python Interpreter – which makes sense as Python is such a versatile language. The best way of executing files appears  to be dependent on multiple factors including the version of Python being used, the actual script and code being executed –  and most importantly user preference.