
How to Write Your First Python 3 Program
Python 3 has become the de facto standard for server automation, scripting, and rapid application development in modern tech stacks. Whether you’re a sysadmin looking to automate repetitive tasks, a developer transitioning from another language, or someone setting up Python environments on servers, understanding how to write and execute your first Python 3 program is essential. This guide will walk you through setting up your development environment, writing your first script, handling common errors, and exploring practical applications that you’ll actually use in production environments.
How Python 3 Works Under the Hood
Python 3 is an interpreted language that gets compiled to bytecode at runtime. When you execute a Python script, the interpreter performs several steps:
- Lexical analysis breaks your source code into tokens
- Parser generates an Abstract Syntax Tree (AST)
- Compiler converts AST to bytecode (.pyc files)
- Python Virtual Machine executes the bytecode
This process happens transparently, but understanding it helps when debugging performance issues or dealing with import problems. The bytecode gets cached in __pycache__
directories, which is why subsequent runs of the same script are faster.
Setting Up Your Python 3 Environment
Before writing your first program, you need a proper Python 3 installation. Most Linux distributions come with Python 3 pre-installed, but the version might be outdated.
Check Your Current Python Version
# Check if Python 3 is installed
python3 --version
# Alternative check
which python3
# On some systems, python points to Python 3
python --version
Installing Python 3 on Different Systems
For Ubuntu/Debian:
sudo apt update
sudo apt install python3 python3-pip python3-venv
For CentOS/RHEL:
sudo yum install python3 python3-pip
# or on newer versions
sudo dnf install python3 python3-pip
For macOS (using Homebrew):
brew install python3
Your First Python 3 Program
Let’s start with the classic “Hello World” but make it more useful for server environments. Create a file called first_program.py
:
#!/usr/bin/env python3
"""
My first Python 3 program
A system information script for servers
"""
import sys
import platform
import datetime
def main():
print("=== System Information ===")
print(f"Python version: {sys.version}")
print(f"Platform: {platform.system()} {platform.release()}")
print(f"Architecture: {platform.architecture()[0]}")
print(f"Processor: {platform.processor()}")
print(f"Current time: {datetime.datetime.now()}")
# Get some basic system stats
try:
import psutil
print(f"CPU usage: {psutil.cpu_percent()}%")
print(f"Memory usage: {psutil.virtual_memory().percent}%")
except ImportError:
print("Install psutil for extended system info: pip3 install psutil")
if __name__ == "__main__":
main()
Running Your Program
# Method 1: Direct execution
python3 first_program.py
# Method 2: Make it executable
chmod +x first_program.py
./first_program.py
# Method 3: Using the python module flag
python3 -m first_program
Understanding the Code Structure
Let’s break down the key components:
- Shebang line (
#!/usr/bin/env python3
): Tells the system which interpreter to use - Docstring: Multi-line comment explaining what the script does
- Imports: Loading necessary modules for functionality
- Function definition: Organizing code into reusable blocks
- Main guard: Ensures code only runs when script is executed directly
Real-World Examples and Use Cases
Server Log Parser
Here’s a practical script that system administrators frequently need:
#!/usr/bin/env python3
"""
Simple log parser for Apache/Nginx logs
Usage: python3 log_parser.py /var/log/apache2/access.log
"""
import sys
import re
from collections import Counter
def parse_log_file(filename):
ip_pattern = r'^(\d+\.\d+\.\d+\.\d+)'
status_pattern = r'" (\d{3}) '
ips = []
status_codes = []
try:
with open(filename, 'r') as file:
for line in file:
# Extract IP addresses
ip_match = re.match(ip_pattern, line)
if ip_match:
ips.append(ip_match.group(1))
# Extract status codes
status_match = re.search(status_pattern, line)
if status_match:
status_codes.append(status_match.group(1))
except FileNotFoundError:
print(f"Error: File {filename} not found")
return
except PermissionError:
print(f"Error: Permission denied reading {filename}")
return
# Display results
print("=== Top 10 IP Addresses ===")
for ip, count in Counter(ips).most_common(10):
print(f"{ip}: {count} requests")
print("\n=== Status Code Distribution ===")
for code, count in Counter(status_codes).most_common():
print(f"{code}: {count}")
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python3 log_parser.py ")
sys.exit(1)
parse_log_file(sys.argv[1])
Configuration File Generator
Another common task is generating configuration files:
#!/usr/bin/env python3
"""
Generate Nginx virtual host configuration
"""
def generate_nginx_config(domain, port=80, root_dir="/var/www/html"):
config_template = f"""server {{
listen {port};
server_name {domain} www.{domain};
root {root_dir};
index index.html index.php;
location / {{
try_files $uri $uri/ =404;
}}
location ~ \.php$ {{
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}}
location ~ /\.ht {{
deny all;
}}
}}"""
filename = f"{domain}.conf"
with open(filename, 'w') as f:
f.write(config_template)
print(f"Configuration written to {filename}")
print(f"Copy to: sudo cp {filename} /etc/nginx/sites-available/")
print(f"Enable with: sudo ln -s /etc/nginx/sites-available/{filename} /etc/nginx/sites-enabled/")
if __name__ == "__main__":
domain = input("Enter domain name: ")
port = input("Enter port (default 80): ") or "80"
root_dir = input("Enter document root (default /var/www/html): ") or "/var/www/html"
generate_nginx_config(domain, int(port), root_dir)
Common Issues and Troubleshooting
Python 2 vs Python 3 Conflicts
One of the most common issues is accidentally running Python 2 instead of Python 3:
# Check what 'python' points to
ls -la $(which python)
# Force Python 3 usage
alias python=python3
# Or use python3 explicitly in scripts
#!/usr/bin/env python3
Module Import Errors
When modules aren’t found, check your Python path:
# Check Python path
python3 -c "import sys; print('\n'.join(sys.path))"
# Install missing modules
pip3 install module_name
# For system-wide installation
sudo pip3 install module_name
Permission Issues
Scripts failing due to permissions:
# Make script executable
chmod +x script.py
# Check file permissions
ls -la script.py
# Run with appropriate permissions
sudo python3 script.py # if root access needed
Python 3 vs Alternatives Comparison
Language | Learning Curve | Performance | System Integration | Best Use Cases |
---|---|---|---|---|
Python 3 | Easy | Moderate | Excellent | Automation, scripting, web development |
Bash | Moderate | Fast | Native | System administration, simple automation |
Go | Moderate | Very Fast | Good | System tools, network services |
Node.js | Easy-Moderate | Fast | Good | Web services, real-time applications |
Best Practices and Performance Tips
Code Organization
- Use virtual environments to isolate dependencies
- Follow PEP 8 style guidelines
- Write docstrings for functions and modules
- Use meaningful variable and function names
- Handle exceptions appropriately
Virtual Environment Setup
# Create virtual environment
python3 -m venv myproject_env
# Activate environment
source myproject_env/bin/activate # Linux/Mac
# myproject_env\Scripts\activate # Windows
# Install packages
pip install requests psutil
# Save dependencies
pip freeze > requirements.txt
# Deactivate when done
deactivate
Performance Considerations
Here’s a simple benchmark comparing different approaches:
#!/usr/bin/env python3
import time
def benchmark_list_comprehension():
start = time.time()
result = [x**2 for x in range(100000)]
end = time.time()
return end - start
def benchmark_traditional_loop():
start = time.time()
result = []
for x in range(100000):
result.append(x**2)
end = time.time()
return end - start
print(f"List comprehension: {benchmark_list_comprehension():.4f}s")
print(f"Traditional loop: {benchmark_traditional_loop():.4f}s")
Security Considerations
When writing Python scripts for server environments:
- Validate all user inputs
- Use subprocess.run() instead of os.system() for shell commands
- Don’t store sensitive data in source code
- Use environment variables for configuration
- Be careful with file permissions on scripts
# Secure way to handle user input
import subprocess
import shlex
def safe_command_execution(user_input):
# Validate input
if not user_input.isalnum():
raise ValueError("Invalid input")
# Use subprocess safely
cmd = ["ls", "-la", user_input]
result = subprocess.run(cmd, capture_output=True, text=True)
return result.stdout
Next Steps and Advanced Topics
After mastering your first Python 3 program, consider exploring:
- Web frameworks like Flask or Django for web applications
- Database integration with SQLAlchemy or Django ORM
- API development with FastAPI or Flask-RESTful
- Task automation with Celery
- Testing with pytest
- Deployment with Docker and CI/CD pipelines
The official Python 3 documentation is an excellent resource for diving deeper into language features. For system administration tasks, the Python Standard Library documentation covers built-in modules that handle everything from file operations to network protocols.
Python 3’s simplicity and powerful standard library make it an ideal choice for server automation, configuration management, and rapid prototyping. The examples in this guide provide a solid foundation for building more complex scripts and applications in production environments.

This article incorporates information and material from various online sources. We acknowledge and appreciate the work of all original authors, publishers, and websites. While every effort has been made to appropriately credit the source material, any unintentional oversight or omission does not constitute a copyright infringement. All trademarks, logos, and images mentioned are the property of their respective owners. If you believe that any content used in this article infringes upon your copyright, please contact us immediately for review and prompt action.
This article is intended for informational and educational purposes only and does not infringe on the rights of the copyright owners. If any copyrighted material has been used without proper credit or in violation of copyright laws, it is unintentional and we will rectify it promptly upon notification. Please note that the republishing, redistribution, or reproduction of part or all of the contents in any form is prohibited without express written permission from the author and website owner. For permissions or further inquiries, please contact us.