How to Run a Python Script in the Ubuntu Terminal

Python is deeply integrated into the Ubuntu Linux ecosystem. In fact, many of the native system utilities you rely on every day are written in Python. This tight integration makes Ubuntu one of the best environments for learning to code, automating server administration tasks, or deploying complex machine learning models.

Whether you have written a simple “Hello World” script in the nano text editor, cloned a complex utility from GitHub, or need to test a data parsing application, you must know how to execute that code from the command line.

This guide explains how to properly run a Python script in the Ubuntu terminal, including how to check your Python version and make your scripts executable.

Step 1: Check Your Python Version

Modern versions of Ubuntu (20.04 and newer) ship exclusively with Python 3 out of the box. The older, legacy Python 2 has been deprecated. Before running a script, it is important to confirm which command your system expects.

  1. Open your Ubuntu terminal.
  2. Type the following command and press Enter:
    python3 --version
  3. The terminal should respond with your installed version, such as Python 3.10.12.

Note: If you are running a very old system, or if a specific script explicitly requires it, you might need to use the python command instead of python3. However, for almost all modern applications, python3 is the correct binary.

Step 2: Run the Script Using the Python Interpreter

The standard way to execute a Python script is to call the Python interpreter directly and pass the path to your script as an argument.

  1. Navigate to the directory where your script is saved using the cd command. For example:
    cd ~/Documents/Scripts
  2. Once you are in the correct directory, run the script by typing python3 followed by the file name:
    python3 my_script.py
  3. Press Enter. The terminal will execute the code and print any output directly below your prompt.

Step 3: Make the Script Executable (Optional)

Typing python3 every time you want to run a script can become tedious. By modifying the file permissions and adding a “shebang” line, you can run the script as if it were a native system command.

  1. Open your script in a text editor like nano:
    nano my_script.py
  2. At the very top of the file, on the absolute first line, add the following “shebang” declaration:
    #!/usr/bin/env python3
    This tells the Ubuntu system to automatically use the Python 3 interpreter when the file is executed. Save and close the file.
  3. Next, grant the file executable permissions using the chmod command:
    chmod +x my_script.py
  4. Now, you no longer need to type python3. You can execute the script directly by typing:
    ./my_script.py

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.