-->

How to host python cgi script with `python -m Simp

2019-01-18 02:37发布

问题:

When I run python -m SimpleHTTPServer 8000 or python -m CGIHTTPServer 8000 in my shell I am hosting the content of my current directory to the internet.

I would like to make the following cgi_script.py work correctly using the above command in the command line when I browse to 192.xxx.x.xx:8000/cgi_script.py

#!/usr/bin/env python
print "Content-Type: text/html"
print
print """\
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>
"""

But this script is displayed literally and not only the "Hello World!" part. Btw I changed the file permissions to 755 for cgi_script.py as well as the folder I am hosting it from.

回答1:

Try with python -m CGIHTTPServer 8000.

Note that you have to move the script to a cgi-bin or htbin directory in order to be runnable.



回答2:

SO doesn't allow me to comment so I'm adding this as a separate answer, addition to rodrigo's.

You can use another parameter cgi_directories which defaults to ['/cgi-bin', '/htbin']. More info here



回答3:

When I ran into this issue I found that depending on which directory you are in when you run the python -m CGIHTTPServer 8000 command yields different results. When attempting to run the command while in the cgi-bin directory the browser continued to return the raw script code. once I cd'ed one level higher and ran the python -m CGIHTTPServer 8000 command again my script began executing.



回答4:

@Bentley4 -ifyou are still not able to do, try importing cgi.

#!C:\Python34\python.exe -u import cgi print ("Content-type:text/html")

HTH



回答5:

in Python3 the command line is simply

python -http.server --cgi 8000


回答6:

This work for me, run the python -m CGIHTTPServer 8000 command same menu level with cgi-bin,and move cgi_script.py into cgi-bin folder.In browser type http://localhost:8000/cgi-bin/cgi_script.py