How To Execute Python Script In Linux – Running Python Scripts Via Command Line

To run a Python script from the Linux command line, you can call the interpreter directly with the script’s filename as an argument. This is the most common method to execute Python code on any Linux distribution, and it works for both Python 2 and Python 3 scripts. Understanding how to execute python script in linux is essential for developers, system administrators, and anyone working with automation or data processing on Unix-like systems.

In this guide, you’ll learn multiple ways to run Python scripts in Linux, from basic commands to advanced techniques like making scripts executable and using shebang lines. We’ll cover troubleshooting common errors and best practices for script execution. By the end, you’ll be able to run any Python script confidently on your Linux machine.

How To Execute Python Script In Linux

Let’s start with the fundamental method. Open your terminal and navigate to the directory containing your Python script. Use the cd command to change directories. Once you’re in the right folder, type python3 script_name.py and press Enter. Replace script_name.py with your actual filename.

If your system uses Python 2, you might need to use python instead of python3. Most modern Linux distributions come with Python pre-installed. Check your Python version with python --version or python3 --version.

Prerequisites For Running Python Scripts

Before executing any Python script, ensure you have Python installed. Open a terminal and run:

  • python3 --version to check Python 3 availability
  • python --version to check Python 2 availability

If Python isn’t installed, use your package manager. For Ubuntu/Debian: sudo apt install python3. For Fedora: sudo dnf install python3. For Arch: sudo pacman -S python.

You also need a text editor to create or modify Python scripts. Common choices include Nano, Vim, or VS Code. The script file should have a .py extension.

Method 1: Using The Python Interpreter Directly

This is the simplest approach. Navigate to your script’s directory and run:

  1. cd /path/to/your/script
  2. python3 myscript.py

The interpreter reads the file and executes the code line by line. If your script requires command-line arguments, add them after the filename: python3 myscript.py arg1 arg2.

This method works for any Python script, regardless of whether it has execute permissions. It’s ideal for testing scripts during development.

Common Issues With Direct Interpreter Calls

If you get “No such file or directory,” double-check the file path. Use ls to list files in the current directory. If you see “command not found,” Python isn’t installed or isn’t in your PATH.

Another common error is “SyntaxError” which indicates code issues. Check for missing colons, indentation problems, or mismatched brackets. Use a linter like pylint to catch errors before running.

Method 2: Making The Script Executable

For scripts you run frequently, make them executable. This allows you to run them like any other command, without typing python3 each time.

  1. Add a shebang line at the top of your script: #!/usr/bin/env python3
  2. Save the file
  3. Make the script executable: chmod +x myscript.py
  4. Run it directly: ./myscript.py

The shebang tells the system which interpreter to use. The chmod +x command adds execute permissions. The ./ prefix tells the shell to look in the current directory.

Adding The Script To Your PATH

To run the script from anywhere without the ./ prefix, add its directory to your PATH. Edit your shell configuration file (e.g., ~/.bashrc or ~/.zshrc) and add:

export PATH="$PATH:/path/to/your/scripts"

Then reload with source ~/.bashrc. Now you can run myscript.py from any directory.

Method 3: Using The Interactive Python Shell

Sometimes you want to test small code snippets without creating a file. Use the interactive Python shell:

  1. Type python3 in the terminal
  2. Write Python code line by line
  3. Press Enter after each line to execute
  4. Exit with exit() or Ctrl+D

This is useful for quick calculations or testing library imports. However, for complex scripts, always use a file.

Method 4: Running Scripts With Arguments

Many Python scripts accept command-line arguments. You can pass them after the script name:

python3 myscript.py --input data.txt --output results.txt

Inside your script, use sys.argv or the argparse module to process these arguments. For example:

import sys
print(sys.argv)

This prints all arguments passed to the script. The first element is always the script name itself.

Method 5: Using The -m Flag For Modules

For Python modules that can be run as scripts, use the -m flag:

python3 -m http.server 8000

This runs the http.server module directly. It’s commonly used for built-in modules like venv, pip, or custom modules installed via pip.

Method 6: Running Scripts In Virtual Environments

Virtual environments isolate Python dependencies for different projects. To run a script inside a virtual environment:

  1. Create a virtual environment: python3 -m venv myenv
  2. Activate it: source myenv/bin/activate
  3. Install dependencies: pip install -r requirements.txt
  4. Run your script: python3 myscript.py
  5. Deactivate when done: deactivate

This ensures your script uses the correct library versions without conflicting with system packages.

Method 7: Using Shebang With Custom Interpreters

If you have multiple Python versions installed, specify the exact interpreter in the shebang:

#!/usr/bin/python3.10

Or use env for portability:

#!/usr/bin/env python3

The env approach finds the first Python 3 in your PATH, making scripts work across different systems.

Method 8: Running Scripts In The Background

For long-running scripts, run them in the background:

nohup python3 myscript.py &

The nohup command prevents the script from stopping when you close the terminal. The & runs it in the background. Output goes to nohup.out by default.

You can also use screen or tmux for more control over background processes.

Method 9: Using Cron To Schedule Scripts

Automate script execution with cron jobs. Edit your crontab:

crontab -e

Add a line like this to run a script daily at 2 AM:

0 2 * * * /usr/bin/python3 /home/user/myscript.py

Cron runs scripts in a minimal environment, so use absolute paths for both the interpreter and script. Redirect output to a log file for debugging.

Method 10: Debugging Script Execution

When scripts fail, use these debugging techniques:

  • Add print() statements to trace execution
  • Use Python’s debugger: python3 -m pdb myscript.py
  • Check error messages carefully—they often point to the exact line
  • Use try-except blocks to catch and log errors
  • Run with -v flag for verbose output: python3 -v myscript.py

Common Errors And Solutions

Here are frequent issues when executing Python scripts:

Error Cause Solution
Permission denied Script not executable chmod +x script.py
No such file Wrong path Use absolute or correct relative path
ModuleNotFoundError Missing dependency pip install module_name
SyntaxError Code error Check indentation and syntax
IndentationError Mixed tabs/spaces Use consistent indentation

Best Practices For Script Execution

Follow these tips for smooth execution:

  • Always use python3 instead of python to avoid ambiguity
  • Keep scripts in organized directories
  • Use version control (Git) for important scripts
  • Add docstrings and comments for clarity
  • Test scripts in a virtual environment first
  • Use absolute paths in cron jobs and systemd services
  • Log output for long-running scripts

Running Python Scripts From Other Programs

You can execute Python scripts from within other programs or scripts. In Bash:

#!/bin/bash
python3 /path/to/script.py

In a Python script, use the subprocess module:

import subprocess
subprocess.run(['python3', 'script.py'])

This allows integration with larger workflows and automation pipelines.

Using Systemd For Service Scripts

For scripts that should run as system services, create a systemd unit file:

[Unit]
Description=My Python Script
[Service]
ExecStart=/usr/bin/python3 /opt/myscript.py
Restart=always
[Install]
WantedBy=multi-user.target

Save to /etc/systemd/system/myscript.service, then run:

sudo systemctl enable myscript
sudo systemctl start myscript

This keeps your script running continuously, restarting if it crashes.

Performance Considerations

For scripts that process large datasets or run frequently:

  • Use python3 -O for optimized bytecode
  • Avoid importing unused modules
  • Use generators instead of lists for large data
  • Profile your code with cProfile
  • Consider using PyPy for CPU-intensive tasks

Security Best Practices

When running scripts from untrusted sources:

  • Review the code before executing
  • Run in a virtual machine or container
  • Use restricted user accounts
  • Avoid running scripts with sudo unless necessary
  • Check for hardcoded passwords or API keys

Frequently Asked Questions

How Do I Run A Python Script In Linux Terminal?

Open terminal, navigate to the script’s directory with cd, then type python3 scriptname.py. Replace “scriptname.py” with your file’s name. Make sure Python is installed.

What Is The Shebang Line In Python Scripts?

A shebang line (#!/usr/bin/env python3) at the top of a script tells the system which interpreter to use. It allows you to run the script directly after making it executable with chmod +x.

Can I Run A Python Script Without Typing Python3?

Yes, by making the script executable (chmod +x script.py) and adding a shebang line. Then run it with ./script.py or add its directory to your PATH.

How Do I Pass Arguments To A Python Script In Linux?

Add arguments after the script name: python3 script.py arg1 arg2. Inside the script, use sys.argv or the argparse module to access them.

What Should I Do If I Get “Command Not Found” When Running Python?

Install Python using your package manager. For Ubuntu: sudo apt install python3. For Fedora: sudo dnf install python3. Verify installation with python3 --version.

Now you have a comprehensive understanding of how to execute python script in linux. Start with the basic methods and gradually explore advanced techniques like virtual environments, cron jobs, and systemd services. Practice with simple scripts first, then move to complex projects. The Linux command line gives you full control over Python script execution, making it a powerful tool for automation and development.