Mac系统下XAMPP运行Python脚本及AJAX调用异常排查
Alright, let's walk through exactly what's missing here—your setup is close, but a few key steps are incomplete that are keeping Apache from running your Python script instead of serving it as plain text.
1. Fix the Shebang Line in Your Python Script
Your script's shebang is missing the critical exclamation mark (!), which tells the system which interpreter to use to run the script. Update the first line to:
#!/usr/local/opt/python/bin/python3.7
Pro tip: Double-check the path is correct by running which python3.7 in your terminal—if it returns a different path, use that instead to avoid interpreter errors.
2. Give the Script Executable Permissions
Apache needs explicit permission to execute your script. Open Terminal, navigate to your htdocs directory, and run:
chmod +x your_script.py
Replace your_script.py with the actual name of your Python file.
3. Update Apache's Directory Configuration to Allow CGI
Adding AddHandler isn't enough on its own—you need to enable CGI execution for your htdocs directory in httpd.conf:
- Open
/Applications/XAMPP/xamppfiles/etc/httpd.confin a text editor (you may need admin access to save changes). - Locate the
<Directory "/Applications/XAMPP/xamppfiles/htdocs">block (adjust the path if you customized your XAMPP setup). - Add
Options +ExecCGIto this block if it's not already present. The block should look something like:<Directory "/Applications/XAMPP/xamppfiles/htdocs"> Options Indexes FollowSymLinks ExecCGI AllowOverride All Require all granted </Directory>
4. Add Required HTTP Headers to Your Python Script
CGI scripts must output a valid HTTP header before any content. Without this, Apache won't recognize it as an executable script and will serve the raw code instead. Update your script to:
#!/usr/local/opt/python/bin/python3.7 print("Content-Type: text/html\n") # Critical: Newline after header to separate it from content print("Hello World!")
The newline (\n) after the header is mandatory—it signals to Apache where the header ends and the actual content begins.
5. Restart Apache
After making all these changes, open the XAMPP Control Panel and restart the Apache server. This ensures all configuration updates take effect.
Once you've completed these steps, your AJAX call should execute the Python script and return "Hello World!" instead of the raw code.
内容的提问来源于stack exchange,提问作者Rajesh s

