Running a Python script on Linux is a fundamental skill for developers, system administrators, and data scientists working in Unix-like environments. While the basic command is straightforward, mastering the various execution methods, permission handling, environment management, and debugging techniques transforms a simple task into a reliable workflow. This guide covers everything from the absolute basics to advanced execution strategies, ensuring your Python code runs reliably across different Linux distributions Easy to understand, harder to ignore..
Understanding the Basics: The Interpreter and the Script
Before diving into execution commands, it is crucial to understand what happens behind the scenes. Which means python is an interpreted language. When you execute a script, the system invokes the Python interpreter, which reads the source code (.py file), compiles it into bytecode, and executes it on the Python Virtual Machine (PVM).
On most modern Linux distributions, Python comes pre-installed. You likely have two major versions available: python3 (the current standard) and potentially python (which may alias to Python 2 on older systems or Python 3 on newer ones like Arch or Fedora). Always explicitly use python3 to avoid version ambiguity.
To verify your installation and version, open your terminal and run:
python3 --version
A typical output looks like Python 3.Think about it: 4. 11.g.If this command fails, install Python using your distribution's package manager (e., sudo apt update && sudo apt install python3 on Debian/Ubuntu or sudo dnf install python3 on Fedora/RHEL).
Method 1: Direct Interpreter Invocation
The most universal way to run a script is by passing the filename as an argument to the python3 command. This method works regardless of file permissions or shebang lines.
Assume you have a file named hello.py with the following content:
#!/usr/bin/env python3
print("Hello, Linux World!")
handle to the directory containing the file using cd and execute:
python3 hello.py
Advantages:
- Explicitly defines which interpreter version runs the code.
- Works on files without execute permissions.
- Ideal for quick testing and debugging.
Pro Tip: Use the -m flag to run library modules as scripts (e.g., python3 -m http.server or python3 -m pytest) Less friction, more output..
Method 2: Executable Scripts with Shebang (The Professional Standard)
For scripts intended for repeated use, automation, or distribution, making the file executable and adding a shebang line is the Linux best practice.
Step 1: Add the Shebang Line
The very first line of your script must be the shebang (#!) followed by the path to the interpreter.
#!/usr/bin/env python3
# Your code follows below...
import sys
print(f"Running on Python {sys.version_info.major}.{sys.version_info.minor}")
Why #!/usr/bin/env python3 instead of #!/usr/bin/python3?
Using env searches the user's $PATH for the python3 executable. This makes your script portable across systems where Python might be installed in /usr/bin, /usr/local/bin, or inside a virtual environment (like /home/user/venv/bin). Hardcoding the path breaks portability.
Step 2: Grant Execute Permissions
Linux treats files as non-executable by default for security. Use chmod (change mode) to add the execute (x) bit Not complicated — just consistent..
chmod +x hello.py
chmod +xadds execute permission for User, Group, and Others.- For stricter security (multi-user systems), use
chmod u+x hello.pyto allow execution only by the file owner.
Step 3: Run Using Relative or Absolute Path
Now you can run the script directly. Because the current directory (.) is usually not in the $PATH for security reasons, you must prefix the filename with ./.
./hello.py
You can also run it using the absolute path from anywhere in the filesystem:
/home/user/scripts/hello.py
Method 3: Running Scripts from Anywhere (Adding to PATH)
If you have utility scripts you want to call globally (like system commands ls or grep), you have two main options:
Option A: Symlink to a Directory in PATH
Standard user-local binary directories like ~/.local/bin or ~/bin are often already in your $PATH. Create a symbolic link:
ln -s /home/user/scripts/hello.py ~/.local/bin/hello
Now you can simply type hello in any terminal window Practical, not theoretical..
Option B: Create a Wrapper Script
For complex applications requiring specific environment variables or virtual environment activation, create a small wrapper shell script in ~/.local/bin:
#!/bin/bash
source /home/user/myproject/venv/bin/activate
exec python3 /home/user/myproject/main.py "$@"
Make this wrapper executable (chmod +x ~/.local/bin/myapp). The "$@" passes all arguments transparently to the Python script Less friction, more output..
Managing Dependencies: Virtual Environments
Running scripts globally with python3 script.py uses the system Python packages. This leads to dependency hell—conflicting library versions between projects. The solution is Virtual Environments (venv) Worth knowing..
Creating and Activating
# manage to your project root
cd my_project
# Create environment (runs once)
python3 -m venv venv
# Activate (run every new terminal session)
source venv/bin/activate
Your shell prompt will change (e.Now, running python3 script., (venv) user@host:~/my_project$). g.py uses the isolated interpreter and pip inside venv/ But it adds up..
Running Without Manual Activation (Shebang Approach)
You can hardcode the venv interpreter in the shebang for cron jobs or systemd services where activation isn't interactive:
#!/home/user/my_project/venv/bin/python3
import requests
print("Running inside venv automatically")
This ensures the script always uses the correct libraries, regardless of how it is invoked And that's really what it comes down to..
Passing Arguments and Reading Input
Scripts become powerful when they accept dynamic input. On the flip side, python accesses command-line arguments via the sys. argv list (standard library) or the more solid argparse module No workaround needed..
Basic sys.argv Example
#!/usr/bin/env python3
import sys
if len(sys.argv) < 2:
print(f"Usage: {sys.argv[0]} ")
sys.exit(1)
name = sys.argv[1]
print(f"Hello, {name}!In real terms, ")
Execution:
. /hello.Because of that, py Alice
# Output: Hello, Alice! Also, ```
* `sys. Practically speaking, argv[0]` is the script name. That said, * `sys. argv[1:]` are the actual arguments.
### Advanced: `argparse` for Production CLI Tools
For flags (`-v`, `--help`), types, and validation, use `argparse`.
```python
#!/usr/bin/env python3
import argparse
parser = argparse.In practice, ")
parser. ArgumentParser(description="Calculate square of a number.add_argument("number", type=int, help="The number to square")
parser.
args = parser.parse_args()
result = args.number ** 2
if args.verbose:
print(f"The square of {args.Even so, number} is {result}")
else:
print(result)
Run with . /square.py 5 -v Easy to understand, harder to ignore..
Handling Input/Output Redirection and Pipes
Linux philosophy treats everything as a file stream (Standard Input stdin, Standard Output stdout, Standard Error stderr). Python scripts integrate easily into pipelines Not complicated — just consistent..