如何在Windows Server IIS部署Python应用?部署后显示代码问题求助
Hey there, let's work through why your Python app is displaying raw code instead of executing on Windows Server 2012's IIS. That #!iusr line you noted in the tutorial is part of the solution, but there are several other critical checks we need to cover:
Add the correct shebang line to your script
While Windows doesn't use shebangs like Unix systems, IIS relies on this line to map your script to the Python interpreter. At the very top of yourapp.py, add:#!C:\full\path\to\your\python.exeReplace the path with your actual Python installation location (e.g.,
#!C:\Python38\python.exe). If you're using a virtual environment, point to thepython.exeinside your venv'sScriptsfolder. This path must match the one you configured in your handler mapping.Verify your handler mapping configuration
Double-check the handler mapping you set up for.pyfiles:- Ensure the executable path includes
%s %sat the end (this passes the script path and arguments to Python). For example:C:\Python38\python.exe "%s" "%s" - Confirm the request path is set to
*.py(to target all Python scripts) - Under Request Restrictions, make sure the Access dropdown is set to
Script(notReadorNone)
- Ensure the executable path includes
Enable the CGI feature in IIS
IIS won't execute Python scripts unless the CGI role service is enabled. To turn it on:- Open Server Manager → Add Roles and Features
- Navigate to Web Server (IIS) → Web Server → Application Development
- Check the CGI box and complete the installation
Adjust application pool settings
Your app pool needs to be configured for non-.NET applications:- Set the .NET CLR Version to
No Managed Code - Confirm the app pool identity (e.g., ApplicationPoolIdentity or IUSR) has Read & Execute permissions on your Python installation directory and website files
- Set the .NET CLR Version to
Test with a minimal script first
Rule out issues with your business logic by testing a simple "Hello World" script:#!C:\Python38\python.exe print("Content-Type: text/html\n") print("<h1>Hello from Python on IIS!</h1>")If this script runs correctly, you can gradually integrate your business code while ensuring each part follows the same execution rules.
Check IIS logs for errors
If you're still stuck, look into IIS's log files (typically stored atC:\inetpub\logs\LogFiles) for specific error codes or messages. 500-level errors often hint at permission issues or misconfigured paths.
内容的提问来源于stack exchange,提问作者Mohit

