How to run a Python script in Linux?

New to Linux or Python? Having Python script to run and feeling lost? See how to run a Python script in Linux.

Running Python scripts on Linux is a fundamental skill for many developers and system administrators, and I’d like to make the process easy to understand.

There are two ways on running Python scripts in Linux.

See also  Creating a Basic Blockchain with Python

Method 1. Python3 command

Using your terminal you can run a script by typing python3 YourScript.py command. That’s it. Your script should run.

Method 2. Using a dot slash

The alternative is to run ./YourScript.py It will run Python script as well.

There are a few things you need to remember:

1. Your script needs to start with

#!/usr/bin/env python3

This shebang line allows the script to be run in Linux by specifying the interpreter. If it’s missing, add it to the first line of your script. This does not alter the script’s logic.

See also  Building Simple Neural Networks with Python

2. Your file needs to be executable. You need to have permission to execute the script to be able to run the Python programm. To change the permission and make the script executable, use the following command:

chmod +x YourScript.py

3. Ensure the Python executable is correctly included in your system’s PATH. Typically, Python is already added to the PATH during installation. If needed, you can manually add it:

export PATH="$PATH:/usr/local/bin/python"