Of course! Here is a comprehensive, step-by-step guide to setting up and running a Python CGI (Common Gateway Interface) script on a Windows machine.

This guide will cover:
- Understanding CGI on Windows: How it works with IIS.
- Prerequisites: What you need installed.
- Step-by-Step Setup: Detailed instructions to configure IIS.
- Writing a Python CGI Script: A simple "Hello, World!" and a more advanced form handler.
- Running and Testing: How to see your script in action.
- Troubleshooting Common Issues: Solving the most frequent problems.
Understanding CGI on Windows
On Windows, the most common web server that supports CGI out-of-the-box is Internet Information Services (IIS). Unlike on Linux where you might use Apache or a simple built-in server, IIS is the standard for Windows.
The core concept is the same:
- A user's browser requests a URL, like
http://localhost/cgi-bin/myscript.py. - IIS sees the
.pyextension and knows it needs to execute this file using the Python interpreter. - IIS sets up special "environment variables" that contain information about the request (e.g., the user's browser, the form data, etc.).
- IIS captures everything the Python script prints to its Standard Output.
- IIS sends this captured output back to the user's browser as the HTTP response.
Prerequisites
-
Python Installed: Make sure you have Python installed on your Windows machine. You can download it from python.org. During installation, crucially, check the box that says "Add Python to PATH". This allows the command line to find
python.exe.
(图片来源网络,侵删) -
IIS Installed: IIS is a Windows feature that you need to enable.
- Press the Windows Key, type "Turn Windows features on or off", and press Enter.
- In the dialog box, expand Internet Information Services.
- Expand World Wide Web Services.
- Expand Application Development Features.
- Check the box for CGI.
- Click OK. Windows will install the necessary files.
Step-by-Step IIS Configuration
Let's set up a directory for our CGI scripts and configure IIS to run them.
Step 3.1: Create a Directory for Your Scripts
It's a best practice to keep your scripts separate from your main website files.
- Open File Explorer.
- Create a new folder. A good location is
C:\inetpub\wwwroot\cgi-bin.C:\inetpub\wwwrootis the default root directory for IIS websites.cgi-binis a conventional name for a directory that holds executable scripts.
Step 3.2: Configure IIS to Execute Python Scripts
Now we'll tell IIS that any file in the cgi-bin folder ending in .py should be executed by Python.

-
Open Internet Information Services (IIS) Manager. You can search for it in the Start Menu.
-
In the left pane, expand your server name, then expand Sites, and click on Default Web Site.
-
In the Actions pane on the right, click on Add Virtual Directory....
- Alias:
cgi-bin(This is the name you'll use in the URL). - Physical path: Browse to the folder you created, e.g.,
C:\inetpub\wwwroot\cgi-bin. - Click OK.
- Alias:
-
Now, select the new
cgi-binvirtual directory in the left pane. -
In the center pane, double-click on Handler Mappings.
-
In the Actions pane on the right, click Add Managed Handler....
- Request path:
*.py - Type:
Python.CgiHandler - Name:
PythonCGI(You can name this anything you like). - Click OK.
- Request path:
-
Important Security Step: By default, IIS might block execution. Make sure the "Execute" permission is set.
- Select the
cgi-binvirtual directory again. - In the center pane, double-click on Handler Mappings.
- Find the
PythonCGIhandler you just created in the list. - Select it and click Request Restrictions... in the Actions pane.
- Go to the Access tab.
- Check the box for Execute (Scripts and Executables).
- Click OK on all the open windows.
- Select the
Your IIS configuration is now complete!
Writing a Python CGI Script
CGI scripts have a special requirement: the very first line of output must be a Content-Type header, followed by a blank line. This tells the browser what kind of data to expect (e.g., HTML, plain text).
Example 1: Simple "Hello, World!" Script
-
Open a text editor (like Notepad++, VS Code, or even Notepad).
-
Save the following code in your
C:\inetpub\wwwroot\cgi-binfolder with the namehello.py.# hello.py print("Content-Type: text/html\n") # The crucial header and a blank line print("<html>") print("<head>") print("<title>Hello from Python CGI!</title>") print("</head>") print("<body>") print("<h1>Hello, World!</h1>") print("<p>This page was generated by a Python CGI script.</p>") print("</body>") print("</html>")
Example 2: Handling Form Data
This script will display the data you send it from an HTML form.
-
First, create an HTML form file. Save it in
C:\inetpub\wwwroot(the main site root) asform.html.<!-- form.html --> <!DOCTYPE html> <html> <head> <title>CGI Form</title> </head> <body> <h1>Enter Your Details</h1> <form action="/cgi-bin/process_form.py" method="post"> Name: <input type="text" name="user_name"> <br><br> Email: <input type="email" name="user_email"> <br><br> <input type="submit" value="Submit"> </form> </body> </html> -
Now, create the Python script to process this form. Save it in
C:\inetpub\wwwroot\cgi-binasprocess_form.py.# process_form.py import cgi import html # The crucial header and a blank line print("Content-Type: text/html\n") # Start of the HTML response print("<html>") print("<head><title>Form Results</title></head>") print("<body>") print("<h1>Form Submitted!</h1>") # Create an instance of FieldStorage to get form data form = cgi.FieldStorage() # Check if the form was submitted with data if "user_name" in form and "user_email" in form: # Use html.escape() to prevent Cross-Site Scripting (XSS) attacks name = html.escape(form.getvalue("user_name")) email = html.escape(form.getvalue("user_email")) print(f"<p>Hello, <strong>{name}</strong>!</p>") print(f"<p>The email address you provided is: {email}</p>") else: print("<p>Error: Form data was not received.</p>") print("</body>") print("</html>")Note: We use the
cgiandhtmlmodules.cgi.FieldStorage()parses the form data, andhtml.escape()sanitizes the input to prevent malicious code injection.
Running and Testing
- Make sure the World Wide Web Publishing Service is running. You can find it in "Services" (
services.msc). - Open your web browser (Chrome, Firefox, Edge, etc.).
- Navigate to your form page:
http://localhost/form.html- You should see the input form. Fill it out and click "Submit".
- You will be redirected to the output from your
process_form.pyscript, which should display the data you entered. - You can also test the simple script directly:
http://localhost/cgi-bin/hello.py- You should see the "Hello, World!" page.
Troubleshooting Common Issues
Issue 1: 404.3 - Forbidden: MIME Type is not handled.
This is the most common error. It means IIS doesn't know how to handle .py files.
- Solution: You likely missed Step 3.2 where you added the
*.pyhandler mapping. Go back and add thePython.CgiHandler.
Issue 2: 500 - Internal Server Error
This means the script was executed, but it crashed or produced invalid output.
- Check the Error Logs: This is your best friend. In IIS Manager, click on your server name -> Logging. The log file path is listed there. Open it in a text editor and look for recent errors.
- Check for Syntax Errors: Did you forget a colon or a quote in your Python script?
- Check the Blank Line: Did you remember to print
Content-Type: text/html\n? The\nrepresents the blank line. This is the #1 cause of 500 errors for CGI.
Issue 3: The browser shows the raw Python code instead of executing it.
This means IIS is treating your script as a plain text file to download, not as an executable.
- Solution: This is the same as the 404.3 error. You need to add the
*.pyhandler mapping in Step 3.2.
Issue 4: python is not recognized as an internal or external command...
This error would appear in the IIS logs if it can't find the Python executable.
- Solution: Make sure you checked "Add Python to PATH" during its installation. If you didn't, you can either reinstall Python or add the Python path (e.g.,
C:\Python39\) manually to your system's PATH environment variable.
