Linux

How To Run Python Script in Linux

Run Python Script in Linux

Python has become the backbone of modern software development, data science, and system administration. Its seamless integration with Linux operating systems makes it an indispensable tool for developers worldwide. Whether you’re a beginner taking your first steps into programming or an experienced professional managing complex automation tasks, understanding how to execute Python scripts in Linux environments is crucial for your success.

Linux distributions ship with Python pre-installed, making script execution straightforward once you master the fundamentals. However, the process involves several methods and considerations that can significantly impact your workflow efficiency and project success. This comprehensive guide will walk you through every aspect of running Python scripts on Linux systems, from basic terminal commands to advanced automation techniques.

You’ll discover multiple execution methods, learn to troubleshoot common issues, and master professional best practices used by seasoned Linux administrators. By the end of this tutorial, you’ll confidently execute Python scripts, manage multiple Python environments, and integrate your scripts into larger automation workflows. The knowledge gained here will serve as your foundation for more advanced Linux system administration and Python development tasks.

Setting Up Your Linux Environment

Checking Python Installation

Before executing any Python script, verify your system’s Python installation status. Most Linux distributions include Python by default, but versions may vary depending on your specific distribution and its release date.

Open your terminal using the keyboard shortcut Ctrl + Alt + T and execute the following commands:

python --version
python3 --version

These commands reveal installed Python versions on your system. Modern Linux distributions typically include both Python 2.7 (legacy) and Python 3.x (current) versions. Ubuntu 20.04 LTS and newer versions prioritize Python 3, while older distributions might default to Python 2.

If Python isn’t installed or you need a specific version, install it using your distribution’s package manager:

For Ubuntu/Debian systems:

sudo apt update
sudo apt install python3 python3-pip

For Red Hat/CentOS/Fedora systems:

sudo yum install python3 python3-pip
# or for newer versions
sudo dnf install python3 python3-pip

For Arch Linux:

sudo pacman -S python python-pip

Opening and Navigating the Terminal

Terminal mastery forms the foundation of effective Python script execution in Linux. The terminal provides direct access to system commands and script execution capabilities that GUI applications cannot match.

Access your terminal through various methods:

  • Press Ctrl + Alt + T (most common shortcut)
  • Click Activities and search “Terminal”
  • Right-click desktop and select “Open Terminal” (if available)
  • Use Alt + F2 and type “gnome-terminal” or “konsole”

Master these essential navigation commands:

pwd                    # Print working directory
ls                     # List directory contents
ls -la                 # Detailed file listing with permissions
cd /path/to/directory  # Change directory
cd ~                   # Navigate to home directory
cd ..                  # Move up one directory level
mkdir new_directory    # Create new directory

Understanding file paths is crucial for script execution. Linux uses forward slashes (/) for path separation, unlike Windows backslashes. Absolute paths start from root (/), while relative paths start from your current location.

Basic Methods to Run Python Scripts

The Standard Python Command Method

The most straightforward approach to executing Python scripts involves using the python3 command followed by your script filename. This method works universally across all Linux distributions and provides immediate script execution.

Navigate to your script’s directory using the cd command, then execute:

python3 script_name.py

Always use python3 instead of python on systems where both Python 2 and Python 3 are installed. This practice ensures your scripts run with the intended Python version and avoids compatibility issues.

For systems with multiple Python 3 versions, specify the exact version:

python3.8 script.py
python3.9 script.py
python3.10 script.py

Check available Python versions with:

ls /usr/bin/python*

This command lists all Python interpreters installed in the standard system directory.

Creating and Running Your First Script

Let’s create a practical example to demonstrate script execution. Create a new file called hello_world.py:

nano hello_world.py

Add the following Python code:

#!/usr/bin/env python3
print("Hello, Linux World!")
print("Python script execution successful!")

# Display system information
import platform
print(f"Operating System: {platform.system()}")
print(f"Python Version: {platform.python_version()}")

Save the file (in nano: Ctrl + X, then Y, then Enter) and execute it:

python3 hello_world.py

The script will output system information along with confirmation messages, demonstrating successful execution. This example showcases basic script structure and system interaction capabilities.

Making Python Scripts Executable

Understanding Shebang Lines

Shebang lines enable direct script execution without explicitly calling the Python interpreter. The shebang (#!/usr/bin/env python3) tells the system which interpreter to use for script execution.

Add this line as the first line of your Python script:

#!/usr/bin/env python3

The /usr/bin/env approach is preferred over hardcoded paths like #!/usr/bin/python3 because it automatically locates the Python interpreter in your system’s PATH. This method provides better portability across different Linux distributions and Python installations.

Alternative shebang variations include:

  • #!/usr/bin/python3 – Direct path to Python 3
  • #!/usr/bin/env python – Generic Python (not recommended)
  • #!/usr/bin/python3.9 – Specific Python version

Setting Execute Permissions

Linux file permissions control script execution capabilities. By default, newly created files lack execute permissions. Grant execute permissions using the chmod command:

chmod +x script_name.py

Verify permissions with the ls -l command:

ls -l script_name.py

Output should show something like:

-rwxr-xr-x 1 user user 156 Aug 13 10:30 script_name.py

The x characters indicate execute permissions for user, group, and others respectively.

Now execute your script directly:

./script_name.py

The ./ prefix tells the shell to look for the script in the current directory. This method provides cleaner execution and resembles how compiled programs run.

Managing Different Python Environments

Working with Multiple Python Versions

Professional development often requires multiple Python versions for different projects. Linux systems commonly have both Python 2.7 (legacy) and various Python 3 versions installed simultaneously.

List all available Python versions:

ls /usr/bin/python*
which python3
whereis python3

Create aliases for frequently used Python versions in your ~/.bashrc file:

alias py38='/usr/bin/python3.8'
alias py39='/usr/bin/python3.9'
alias py310='/usr/bin/python3.10'

After adding aliases, reload your shell configuration:

source ~/.bashrc

Now execute scripts with version-specific commands:

py38 data_analysis.py
py39 web_scraper.py
py310 machine_learning.py

Virtual Environments

Virtual environments isolate project dependencies and prevent version conflicts between different Python projects. Create isolated environments for each project to maintain clean dependency management.

Install the virtual environment package:

sudo apt install python3-venv  # Ubuntu/Debian

Create a new virtual environment:

python3 -m venv myproject_env

Activate the virtual environment:

source myproject_env/bin/activate

Your terminal prompt will change to indicate the active environment:

(myproject_env) user@hostname:~$

Install project-specific packages:

pip install requests numpy pandas

Run scripts within the virtual environment:

python script.py  # Uses the virtual environment's Python

Deactivate the environment when finished:

deactivate

Virtual environments ensure consistent package versions across different systems and prevent system-wide package conflicts.

Advanced Execution Methods

Running Scripts with Arguments

Command-line arguments make scripts flexible and reusable. Python’s sys.argv module captures arguments passed during script execution.

Create a script called argument_example.py:

#!/usr/bin/env python3
import sys

print(f"Script name: {sys.argv[0]}")
print(f"Number of arguments: {len(sys.argv) - 1}")

if len(sys.argv) > 1:
    print("Arguments provided:")
    for i, arg in enumerate(sys.argv[1:], 1):
        print(f"  Argument {i}: {arg}")
else:
    print("No arguments provided")

# Example: Process a filename argument
if len(sys.argv) > 1:
    filename = sys.argv[1]
    print(f"Processing file: {filename}")

Execute with arguments:

python3 argument_example.py file1.txt file2.txt "file with spaces.txt"

For more sophisticated argument handling, use the argparse module:

#!/usr/bin/env python3
import argparse

parser = argparse.ArgumentParser(description='Process some files.')
parser.add_argument('files', nargs='+', help='Files to process')
parser.add_argument('--verbose', '-v', action='store_true', help='Verbose output')

args = parser.parse_args()

for file in args.files:
    if args.verbose:
        print(f"Processing {file} with verbose output")
    else:
        print(f"Processing {file}")

Background Execution and Services

Background execution allows scripts to run independently of terminal sessions. This capability is essential for long-running processes, server applications, and automated tasks.

Run a script in the background:

python3 long_running_script.py &

The & operator sends the process to the background, returning control to your terminal immediately.

For persistent background execution that survives terminal closure:

nohup python3 long_running_script.py &

Monitor background processes:

jobs           # List active jobs
ps aux | grep python  # Find Python processes
kill %1        # Kill job number 1
kill PID       # Kill process by ID

Create a simple systemd service for permanent script execution:

Create /etc/systemd/system/myscript.service:

[Unit]
Description=My Python Script
After=network.target

[Service]
Type=simple
User=myuser
WorkingDirectory=/path/to/script
ExecStart=/usr/bin/python3 /path/to/script/myscript.py
Restart=always

[Install]
WantedBy=multi-user.target

Enable and start the service:

sudo systemctl enable myscript.service
sudo systemctl start myscript.service
sudo systemctl status myscript.service

Integration with Bash Scripts

Calling Python from Bash Scripts

Bash scripts can orchestrate complex workflows involving multiple Python scripts. This integration enables powerful automation scenarios combining shell utilities with Python’s capabilities.

Create a bash script automation.sh:

#!/bin/bash

echo "Starting automation workflow..."

# Change to script directory
cd /path/to/python/scripts

# Run data collection script
echo "Running data collection..."
python3 collect_data.py

# Check if data collection succeeded
if [ $? -eq 0 ]; then
    echo "Data collection successful"
    
    # Run data processing script
    echo "Processing data..."
    python3 process_data.py
    
    # Generate reports
    echo "Generating reports..."
    python3 generate_reports.py
    
else
    echo "Data collection failed. Aborting workflow."
    exit 1
fi

echo "Automation workflow completed successfully"

Make the bash script executable:

chmod +x automation.sh

Execute the automation workflow:

./automation.sh

Automation and Scheduling

Cron jobs enable automatic script execution at specified intervals. This feature is perfect for maintenance tasks, data backups, report generation, and system monitoring.

Edit your crontab:

crontab -e

Add entries for scheduled execution:

# Run every day at 2:30 AM
30 2 * * * /usr/bin/python3 /home/user/scripts/daily_backup.py

# Run every Monday at 9:00 AM
0 9 * * 1 /usr/bin/python3 /home/user/scripts/weekly_report.py

# Run every 15 minutes
*/15 * * * * /usr/bin/python3 /home/user/scripts/monitor.py

Cron syntax breakdown:

  • Minute (0-59)
  • Hour (0-23)
  • Day of month (1-31)
  • Month (1-12)
  • Day of week (0-7, where 0 and 7 are Sunday)

View current cron jobs:

crontab -l

Create comprehensive logging for scheduled scripts:

#!/usr/bin/env python3
import logging
import datetime

# Configure logging
logging.basicConfig(
    filename='/var/log/myscript.log',
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)

logging.info("Script execution started")
# Your script logic here
logging.info("Script execution completed")

Troubleshooting Common Issues

Permission and Path Errors

Permission denied errors frequently occur when scripts lack proper execution permissions or when accessing restricted files and directories.

Problem: “Permission denied” when executing script
Solution: Grant execute permissions

chmod +x script.py

Problem: “Python not found” or “command not found”
Solution: Check Python installation and PATH

which python3
echo $PATH
export PATH=$PATH:/usr/bin

Problem: “No such file or directory”
Solution: Verify script location and use absolute paths

ls -la script.py
/usr/bin/python3 /full/path/to/script.py

Problem: “ModuleNotFoundError” for installed packages
Solution: Check virtual environment activation or install missing packages

pip3 list
pip3 install module_name

Version and Compatibility Issues

Python version conflicts create compatibility problems, especially when switching between Python 2 and Python 3 or when using version-specific features.

Problem: Script works in Python 3 but fails with “python” command
Solution: Always use python3 explicitly

python3 script.py  # Not python script.py

Problem: Import errors for standard library modules
Solution: Check Python version compatibility

import sys
print(sys.version_info)

Problem: Syntax errors in seemingly correct code
Solution: Verify Python version and use appropriate syntax

python3 -m py_compile script.py  # Check syntax

Problem: Package installation conflicts
Solution: Use virtual environments for isolation

python3 -m venv project_env
source project_env/bin/activate
pip install requirements.txt

Create a requirements.txt file for reproducible environments:

pip freeze > requirements.txt  # Generate requirements
pip install -r requirements.txt  # Install from requirements

Best Practices and Professional Tips

Script Organization and Structure

Professional Python script organization enhances maintainability, readability, and collaboration. Follow established conventions to create clean, professional code structure.

Use descriptive filenames that indicate script purpose:

  • data_processor.py instead of script1.py
  • user_authentication.py instead of auth.py
  • database_backup.py instead of backup.py

Organize scripts in logical directory structures:

project/
├── scripts/
│   ├── data_processing/
│   │   ├── clean_data.py
│   │   └── validate_data.py
│   ├── utilities/
│   │   ├── file_handler.py
│   │   └── logger.py
│   └── main.py
├── config/
│   └── settings.py
└── logs/
    └── application.log

Include comprehensive documentation and error handling:

#!/usr/bin/env python3
"""
Data Processing Script
Author: Your Name
Date: 2025-08-13
Description: Processes customer data files and generates reports
"""

import sys
import logging
from datetime import datetime

def main():
    """Main script execution function"""
    try:
        # Script logic here
        logging.info("Script executed successfully")
        return 0
    except Exception as e:
        logging.error(f"Script execution failed: {e}")
        return 1

if __name__ == "__main__":
    sys.exit(main())

Security and Performance Considerations

Security awareness prevents vulnerabilities and ensures safe script execution in production environments. Performance optimization reduces resource consumption and improves user experience.

Implement input validation and sanitization:

import os
import re

def validate_filename(filename):
    """Validate filename to prevent directory traversal attacks"""
    if '..' in filename or filename.startswith('/'):
        raise ValueError("Invalid filename")
    return re.match(r'^[a-zA-Z0-9._-]+$', filename) is not None

Use environment variables for sensitive configuration:

import os

DATABASE_PASSWORD = os.environ.get('DB_PASSWORD')
if not DATABASE_PASSWORD:
    raise ValueError("Database password not set in environment")

Monitor resource usage and optimize performance:

import psutil
import time

def monitor_resources():
    """Monitor script resource usage"""
    process = psutil.Process()
    print(f"Memory usage: {process.memory_info().rss / 1024 / 1024:.2f} MB")
    print(f"CPU usage: {process.cpu_percent():.2f}%")

# Profile script execution time
start_time = time.time()
# Your script logic here
execution_time = time.time() - start_time
print(f"Execution time: {execution_time:.2f} seconds")

Alternative Methods and Tools

Using Python IDEs and IDLE

Integrated Development Environments (IDEs) provide graphical interfaces for script development and execution. While command-line execution remains essential, IDEs offer debugging capabilities and enhanced development experiences.

Launch IDLE from terminal:

idle3  # Python 3 IDLE

Popular Linux-compatible Python IDEs include:

  • PyCharm: Professional IDE with extensive features
  • Visual Studio Code: Lightweight editor with Python extensions
  • Vim/Neovim: Terminal-based editor with Python plugins
  • Sublime Text: Fast, customizable text editor

Configure Visual Studio Code for Python development:

sudo snap install code
code --install-extension ms-python.python

Text Editors and Script Development

Terminal-based editors enable script development directly on servers and remote systems without graphical interfaces.

Vim/Neovim configuration for Python:
Create ~/.vimrc:

syntax on
set number
set tabstop=4
set shiftwidth=4
set expandtab
set autoindent
filetype plugin indent on

Nano editor basics:

nano script.py       # Open file
Ctrl + X            # Exit
Ctrl + O            # Save
Ctrl + K            # Cut line
Ctrl + U            # Paste

Emacs for Python development:

emacs script.py

These editors provide syntax highlighting, indentation management, and basic IDE features directly in the terminal environment.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button