Execute Python Code
There are multiple ways to execute a Python code.
Interactive Mode
- Enter Python interactive mode, just by running
pythonat the command line (Make sure the PATH environment variable is updated with Python’s path). - You can execute statements and get the results instantly, in this mode. The code is converted into machine code and executed by the Interpreter on the fly.
- The data (for example, variable values) persists within the session and can be reused in the subsequent statements.
- This is referred to as REPL, short for Read, Eval, Print & Loop.
IDLE
- IDLE is the Intergrated Development Environment (IDE) that comes pre-installed with Python’s installation. It can also be used to interact with the Python interpreter.
Using a File
- The problem with interactive mode is that the code executed is lost after the session gets closed. If you want to execute a specific piece of code again & again, it’s better to keep it in a file.
- These files are called modules in Python and they are discussed in later part of this book.
- To execute the code in the file, simply pass the file path as an argument to the
pythoncommand. Ex:python filename.py - You can also include shebang in the file (
#! /usr/local/bin/python) to provide Python location and execute the file directly as./filename.py, without the need forpythoncommand.- Make sure necessary permissions (
chmod 755) are added to the file, to make it executable. - If you aren’t sure about the python location and would want to rely on PATH env variable to find it, you can change the shebang to
#! /usr/bin/env python(Change the path ofenvutility if needed. It's usually found in/binor/usr/binor/usr/local/binor/usr/sbin).
- Make sure necessary permissions (
Other Methods
- There are, of course, other methods to execute Python statements. You can use advanced IDEs such as PyCharm, to manage your python packages.
- You can also embed Python interpreter into C or C++ applications, and therefore execute Python statements. This is a bit advanced and isn’t covered in this documentation (May be later).
