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.

This python3 YourScript.py command explicitly invokes the Python 3 interpreter to execute your script. This method is straightforward and ensures that the script is run using the Python 3 version (if you have multiple Python versions installed), regardless of whether the script has execute permissions set or a shebang line.

See also  How To Exit A Function In 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

The shebang line (#!/usr/bin/env python3) is a special line at the beginning of a script that tells the operating system which interpreter should be used to execute the file. #!/usr/bin/env python3 is a portable way to specify Python 3, as env will search the system’s PATH for the python3 executable. Without a shebang line, the Linux shell doesn’t inherently know to execute the file with Python when using the ./YourScript.py command.

See also  Calculate age from date of birth in 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

The chmod +x YourScript.py command modifies the file’s permissions to make it executable. In Linux, files need execute permissions set to be run directly as programs. The +x option adds execute permissions for all users. Without execute permissions, the system will not allow you to run the script directly using ./YourScript.py, even with a valid shebang line.

See also  How to uninstall Numpy?

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.

To further enhance your Python development workflow in Linux, consider exploring: virtual environments (venv or virtualenv), package managers (pip), text editors/IDEs (e.g., VS Code, Sublime Text, Vim, Emacs) and script automation (e.g., cron).