Hi, I can run python files from web browser at the address http://localhost/cgi-bin/myfile.py but I want to run them at the address http://localhost:anyport/ , how can I do?
I read a book on Python and it said that I had to activate the web server to understand python code, using only 3 lines of code, put them in a .py file and run the script and then I can type "http://localhost:anyport/" in the address bar of the web browser and see it works.
I did it but it didn't work, here are the 3 lines of code:
#!usr/bin/python
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
HTTPServer(('localhost',8000), SimpleHTTPRequestHandler).serve_forever()
Save these as "activate.py"
I'm a little confused here, it said "run this script" and I wonder if "run" here means run the "activate.py" with python.exe??? If so, I did that and after typing "http://localhost:8000", the web browser showed a cannot display page (the address does not exist). Could you please make it clear, they say programming web with python is very easy, but I don't feel its ease, it's even not easier than PHP.
Your help would be highly appreciated! Thanks!
PS: Ah, what about the #!usr/bin/python ? Is it the same on all machine installed with Python? What is it?, Thanks
UPDATE
In fact, the script I saved as "activate.py" didn't run successfully, the error said "No module named BaseHTTPServer", How could I fix this?
Thank you!
解决方案The three lines of code you list are python code.
You run the script using python.exe
The first two lines import some python classes from various modules.
The third line creates a "HTTPServer". It then calls the serve_forever() function of the HTTPServer.
See: http://docs.python.org/py3k/library/http.server.html[^]
Presumably that function continously listens on the designated port ('localhost', 8000) and handles the requests with SimpleHTTPRequestHandler
See: http://docs.python.org/library/simplehttpserver.html[^]
Quote:This class serves files from the current directory and below, directly mapping the directory structure to HTTP requests.
SimpleHTTPServer doesn't handle CGI files, but just serves static html.
There is a python class that does that:
http://docs.python.org/library/cgihttpserver.html[^]
However, there isn't any reason you should be using any of those to accomplish your stated goal.
You already have a webserver running (Apache?) -- you should be configuring that to serve the pages you want from the directory you want on the port you want. (See the documentation for your web server to figure out how to do that.)
If you are just trying to learn python for programming web pages, then stick with running them from http://localhost/cgi-bin/myfile.py -- don't bother with trying to run a webserver in python as well.