Of course! This is a very common and useful setup. Integrating Python with XAMPP's Apache server allows you to run Python scripts as if they were web pages, enabling you to use powerful Python libraries (like for data analysis, machine learning, or web scraping) directly from your browser.

Here’s a complete guide on how to set up and use Python with XAMPP's Apache server.
The Core Concept: The mod_wsgi Module
By default, Apache doesn't know how to execute Python code. To make it happen, we need to use a special module called mod_wsgi.
mod_wsgiis an Apache module that hosts Python applications, allowing Apache to serve dynamic content generated by Python scripts.- It acts as a bridge between your web server (Apache) and your Python interpreter.
There are two main ways to use mod_wsgi:
- Embedded Mode:
mod_wsgiis compiled directly into the Apache process. This is simpler to set up but is less flexible and can be harder to debug. - Daemon Mode (Recommended):
mod_wsgiruns a separate, long-running Python process (a "daemon"). Apache communicates with this daemon to serve Python content. This is more efficient, more stable, and the industry standard.
We will focus on setting up the Embedded Mode first because it's the easiest way to get started and understand the concept.

Method 1: Embedded Mode (Easiest for Beginners)
This method involves adding a few lines to your Apache configuration file to tell it how to handle .py files.
Step 1: Install mod_wsgi
First, you need to install the mod_wsgi module on your system. The version must match your Python and Apache versions.
-
On Windows:
- Go to the official
mod_wsgidownload page: https://modwsgi.readthedocs.io/en/develop/installation.html - Scroll down to the "Binaries" section for Windows.
- Download the
.whl(Wheel) file that matches your system (32-bit or 64-bit) and Python version (e.g.,cp311for Python 3.11). - Open a Command Prompt as an Administrator.
- Navigate to the directory where you downloaded the file.
- Install it using
pip. For example:pip install mod_wsgi‑4.9.72‑cp311‑cp311‑win_amd64.whl
- Go to the official
-
On Linux (Debian/Ubuntu):
(图片来源网络,侵删)sudo apt update sudo apt install libapache2-mod-wsgi-py3
This will automatically install the module and enable it for you.
-
On macOS (using Homebrew):
brew install mod-wsgi
Step 2: Configure Apache
Now, we need to tell Apache to use this module.
-
Find your Apache Configuration File:
- In the XAMPP Control Panel, click the Config button next to Apache and select httpd.conf.
- This will open the main Apache configuration file in a text editor (like Notepad++).
-
Load the Module:
- Press
Ctrl+Fand search forLoadModule. You will see a list of already loaded modules. - Add the following line at the end of the
LoadModulesection. The path might be slightly different on your system, so find the correct path by looking at wheremod_wsgi.sowas installed (e.g., in your PythonScriptsfolder or your Apachemodulesfolder).
# For Windows, the path will be something like this: LoadModule wsgi_module "C:/Python39/python.exe/mod_wsgi.py" # Or if it's in the Apache modules folder: # LoadModule wsgi_module modules/mod_wsgi-py39-win32.so # For Linux, it's usually: # LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi.so
- Press
-
Configure a Python Handler:
- Add the following lines at the bottom of the
httpd.conffile. This tells Apache that any file ending in.pyshould be executed as a WSGI script.
# Add a handler for Python files <FilesMatch "\.py$"> SetHandler wsgi-script </FilesMatch> # Optional: Set a timeout for your scripts (in seconds) WSGIScriptTimeout 30 - Add the following lines at the bottom of the
-
Save and Restart Apache:
- Save the changes to
httpd.conf. - In the XAMPP Control Panel, stop and then restart the Apache service.
- Save the changes to
Step 3: Create a Test Python Script
-
Place a Python file in your XAMPP web root directory. This is usually
C:/xampp/htdocs/. -
Create a file named
hello.pyand add the following code:def application(environ, start_response): status = '200 OK' output = b'Hello from Python! This is a dynamic web page.' response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(output)))] start_response(status, response_headers) return [output]Note: The
applicationfunction is the standard entry point for a WSGI application. It must be namedapplication. -
Open your web browser and navigate to:
http://localhost/hello.py
You should see the text: Hello from Python! This is a dynamic web page. If you see this, congratulations, it's working!
Method 2: Daemon Mode (Recommended for Production)
Daemon mode is more complex to set up but is much better for performance and reliability. It isolates your Python application from Apache.
Step 1: Install mod_wsgi (Same as before)
Make sure you have mod_wsgi installed as described in Method 1.
Step 2: Configure Apache for Daemon Mode
-
Open your
httpd.conffile (from XAMPP's Config menu). -
Add the following configuration at the bottom of the file. Read the comments carefully to understand what each part does.
#--------------------------------------------------------------------- # mod_wsgi Daemon Mode Configuration #--------------------------------------------------------------------- # Define the path to your Python executable. # This is crucial for Windows. WSGIPythonHome "C:/Users/YourUser/AppData/Local/Programs/Python/Python311" # CHANGE THIS # On Linux, you might not need this line, or it could be: # WSGIPythonHome /usr/bin/python3 # Define a daemon process. We'll call it 'my-python-app'. WSGIDaemonProcess my-python-app \ python-home="C:/Users/YourUser/AppData/Local/Programs/Python/Python311" \ # CHANGE THIS processes=2 \ threads=15 \ display-name=%{GROUP} # Associate the 'my-python-app' daemon with a specific directory. # This tells Apache that any request for a file in 'C:/xampp/htdocs/myapp' # should be handled by our daemon. WSGIScriptAlias /myapp "C:/xampp/htdocs/myapp/app.wsgi" # CHANGE THIS PATH # Apply the daemon process to the directory. <Directory "C:/xampp/htdocs/myapp"> # CHANGE THIS PATH WSGIProcessGroup my-python-app WSGIApplicationGroup %{GLOBAL} Require all granted </Directory>What you need to change:
WSGIPythonHome: Set this to the installation directory of your Python version.WSGIDaemonProcess: Make sure thepython-homematches your Python path.WSGIScriptAlias: This is the URL path (/myapp) and the path to your WSGI entry point file (app.wsgi).<Directory>: This must be the directory containing your application files.
-
Save and Restart Apache.
Step 3: Create a Sample Project
Now, let's create the project structure that the configuration above expects.
- Inside
C:/xampp/htdocs/, create a new folder namedmyapp. - Inside
myapp, create two files:app.wsgiandapp.py.
File 1: C:/xampp/htdocs/myapp/app.py (Your main application logic)
# This is a simple Flask-like application, but we don't need Flask.
def simple_app(environ, start_response):
"""A simple WSGI application."""
status = '200 OK'
headers = [('Content-type', 'text/html; charset=utf-8')]
start_response(status, headers)
# You can access request data from environ
html_content = f"""
<html>
<head><title>Python via Daemon Mode</title></head>
<body>
<h1>Hello from Python in Daemon Mode!</h1>
<p>This page is served by a separate Python process, which is more efficient.</p>
<p>Request Path: {environ['PATH_INFO']}</p>
</body>
</html>
"""
return [html_content.encode('utf-8')]
# You can also have multiple functions and route them
def another_app(environ, start_response):
status = '200 OK'
headers = [('Content-type', 'text/plain')]
start_response(status, headers)
return [b"This is another Python application.".encode('utf-8')]
File 2: C:/xampp/htdocs/myapp/app.wsgi (The WSGI entry point)
This file tells mod_wsgi which function from your Python code to run.
import sys # Add the directory containing your app.py to the Python path sys.path.insert(0, 'C:/xampp/htdocs/myapp') # CHANGE THIS IF NEEDED # Import your application function from app.py from app import simple_app # This is the variable mod_wsgi will look for. # Assign your application function to it. application = simple_app # If you wanted to use 'another_app', you would do: # application = another_app
- Open your browser and navigate to:
http://localhost/myapp
You should see the HTML page generated by your Python script running in a dedicated daemon process.
Troubleshooting Common Issues
-
Internal Server Error (500):
- Check your Apache
error.logfile (inC:/xampp/apache/logs/). It will contain the exact Python error traceback, which is the key to fixing the problem. - Make sure your Python syntax is correct.
- Ensure all file paths in
httpd.confare correct. - On Windows, make sure
WSGIPythonHomepoints to the correct Python directory.
- Check your Apache
-
Forbidden Error (403):
- This is usually a permissions issue. Make sure the user that Apache is running as (e.g.,
SYSTEMon Windows) has read/execute permissions for your Python files and their directories. - Check the
Require all granteddirective in your<Directory>block.
- This is usually a permissions issue. Make sure the user that Apache is running as (e.g.,
-
The requested URL was not found on this server (404):
- Double-check the URL you are typing in the browser.
- Ensure that
WSGIScriptAliasand the<Directory>block inhttpd.confpoint to the correct paths.
