# Running Python Scripts on Apache (cPanel)

This guide demonstrates how to run Python scripts on a standard Apache web server, such as those provided by cPanel shared hosting. The most common method for simple scripts in this environment is using **CGI (Common Gateway Interface)**.

## Prerequisites

1.  **cPanel Hosting**: Access to a hosting account with Python installed (most Linux hosts have Python pre-installed).
2.  **File Access**: Access via File Manager or FTP/SSH.

## Step 1: Create the Script

Create a file named `hello.py`.

**Crucial Requirements:**
1.  **Shebang Line**: The very first line must point to the Python interpreter. On most cPanel servers, this is `#!/usr/bin/env python3` or `#!/usr/bin/python3`.
2.  **Content-Type Header**: You must print the HTTP header before any other output, followed by a blank line.

```python
#!/usr/bin/env python3
import cgitb
import sys

# Enable detailed error reporting (useful for debugging 500 errors)
cgitb.enable()

# 1. Print HTTP Header
print("Content-Type: text/html\n")

# 2. Print HTML Content
print("<!DOCTYPE html>")
print("<html>")
print("<head>")
print("<title>Python on Apache</title>")
print("</head>")
print("<body>")
print("<h1>Hello from Python!</h1>")
print(f"<p>Python Version: {sys.version}</p>")
print("</body>")
print("</html>")
```

## Step 2: Upload and Permissions

1.  Upload `hello.py` to your `public_html` or `cgi-bin` folder.
2.  **Set Permissions**: You must change the file permissions to **755** (rwxr-xr-x).
    *   In cPanel File Manager: Right-click file -> Change Permissions.
    *   Via SSH: `chmod 755 hello.py`

## Step 3: Configure Apache (.htaccess)

By default, Apache might only execute scripts in the `cgi-bin` directory or might treat `.py` files as plain text. To execute them in `public_html`, you need to modify your `.htaccess` file.

Create or edit the `.htaccess` file in the same directory as your script:

```apache
Options +ExecCGI
AddHandler cgi-script .py
```

## Troubleshooting

*   **500 Internal Server Error**:
    *   **Permissions**: Ensure the file is 755.
    *   **Line Endings**: If you wrote the script on Windows, it might have Windows line endings (`\r\n`). Convert it to Unix (`\n`) using a text editor (Notepad++ -> Edit -> EOL Conversion -> Unix) or `dos2unix` command.
    *   **Shebang**: Ensure the path `#!/usr/bin/env python3` is correct for your server.
*   **Code Displayed as Text**:
    *   Apache doesn't know it should execute the file. Check your `.htaccess` configuration (`AddHandler`).

[[programming/python/python]]