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.

Method 1. Python3 command

You can easily run a Python script using the terminal by typing the following command:

python3 YourScript.py

This will execute the script as long as Python is installed on your system.

See also  Quantum Algorithms Simplified with Python

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  Adding Points to an Existing Plot in Matplotlib

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"

This ensures the system can locate the Python interpreter.

See also  Exploring Advanced Features of Flask