The Interpreter

    To fire up the Python interpreter, open up your terminal/console application, and type python or python3 (depending on your installation). You should see something that looks like this:

    This is known as the Python interpreter, and is a REPL (Read–Eval–Print Loop). This allows you to type Python code, import modules, and interact with code you’ve written without having to write files to disk, in an interactive manner. This interactive mode is one of Python’s super-powers, compared some other programming languages.

    To run a Python script (that you’ve either written or downloaded from the internet), simply run the following:

    1. $ python3 name-of-script.py

    This will tell Python to load and execute the script provided.

    Sometimes, a script will not run because it does not have the necessary dependencies installed. You’ll normally see this come across as a ModuleNotFoundError, embedded within a confusing (if you’re new) exception message:

    1. $ pipenv install requests

    Note

    If you downloaded a directory of files, check for a or a requirements.txt file in the root directory. If it is present, simply running $ pipenv install will install all of the dependencies needed, without you needing to specify them.

    This will install requests into a virtual environment. Then, you have two options for running your script:

    The first option is to use $ pipenv run:

    The second option is to run $ pipenv shell, which will spawn a new shell where python is the one from your virtual environment:

    1. (project-vHd3e) $ python name-of-script.py

    Python Interpreter Tricks

    There are a few tricks the interpreter has up its sleeve that I recommend you utilize on a regular basis.

    The _ variable can be used to reference the last thing that was eval’d (e.g. automatically printed to the screen). For example:

    Very useful when using the interactive interpreter!

    The second trick is PYTHONDONTWRITEBYTECODE. If you set this environment variable (e.g. in your ~/.bashrc file or similar), Python won’t write *.pyc files to disk, which is great, because they are incredibly annoying.

    I’ve been using this environment variable for 7+ years for development and have never had any problems because of it.

    This flag will run the script, like usual, but will then drop you into a REPL afterwards that has all the locals and globals from the script loaded, for your interactive pleasure. Very useful.