34

I am using Windows 7 and Python 3.4.3. I would like to run this simple helloworld.py file in my browser:

print('Content-Type: text/html')
print( '<html>')
print( '<head></head>')
print( '<body>')
print( '<h2>Hello World</h2>')
print( '</body></html>')

What I do is:

1) Go to command line C:\Python (where python is installed)

2) run: python -m http.server

3) Got to Firefox and type http://localhost:8000/hello.py

However, instead of "Hello World", the browser just prints the content of the hello.py file.

How can I fix it?

13
  • 1
    your webserver isnt "running python". your python is running a webserver. Commented May 28, 2015 at 20:29
  • You should edit your original question instead of just reposting it. Commented May 28, 2015 at 20:29
  • 1
    @IanAuld, my other question was regarding configuring WAMP. This question is regarding http.server. No reposting - this is a different question Commented May 28, 2015 at 20:33
  • 1
    @Yura This tutorial will cover a lot of things but is pretty easy to follow along with. This one is much more basic (and slightly out dated) but will show you the basics. Commented May 28, 2015 at 21:04
  • 1
    By the way you do not type in 'localhost:8000/hello.py' do it WITHOUT 'hello.py' Commented May 28, 2015 at 21:55

3 Answers 3

34

From the http.server docs:

CGIHTTPRequestHandler can be enabled in the command line by passing the --cgi option:

$ python3 -m http.server --bind localhost --cgi 8000

Put your script into cgi_directories:

This defaults to ['/cgi-bin', '/htbin'] and describes directories to treat as containing CGI scripts.

Open in the browser:

$ python -mwebbrowser http://localhost:8000/cgi-bin/hello.py

where hello.py:

#!/usr/bin/env python3
print("Content-Type: text/html\n")
print("<!doctype html><title>Hello</title><h2>hello world</h2>")

I had to make it executable on POSIX: chmod +x cgi-bin/hello.py.

Sign up to request clarification or add additional context in comments.

14 Comments

can you test my python3 script if it really works. I do not want to install python3 right now or use some online python because those work some different.
@Tom-OliverHeidel: sure. What commands do you want me to run and what do you expect to happen (define "really works": do you care about multiple concurrent clients, security, buffers, etc)?
scroll down a bit - the other answer is mine.
@Yura: 1. have you put hello.py into cgi-bin directory? 2. Have you appended --cgi as shown above? 3. Have you visited localhost:8000/cgi-bin/hello.py (note: cgi-bin in url)? 4. Have your added additional "\r\n" after the http header?
@Yura is using windows so. J.F. Sebastian he will not have a cgi-bin by default. I guess he is just testing some python at all.
|
5

I created a complete example for a friend. It is a complete demo you can run with 8 simple copy-paste ready lines of code. Enjoy.

echo -e "\n\n    Usage: after running this script, visit http://localhost:8000/cgi-bin/hello    \n\n"
mkdir /tmp/cgi-bin/
cat > /tmp/cgi-bin/hello <<EOF
#!/bin/bash
echo -e "Content-Type: text/plain\n\n"; date; echo; env
EOF
chmod +x /tmp/cgi-bin/hello
(cd /tmp; python3 -m http.server --cgi 8000)

1 Comment

Thanks !!! You give me a very useful solution and I didn't spend lot of time
2

I did this some time ago for Python2.7

from BaseHTTPServer import BaseHTTPRequestHandler

class GetHandler(BaseHTTPRequestHandler):

    def do_HEAD(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()

    def do_GET(self):
        x = self.wfile.write
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        # <--- HTML starts here --->
        x("<html>")
        # <--- HEAD starts here --->
        x("<head>")
        x("<title>Title goes here!</title>")
        x("</head>")
        # <--- HEAD ends here --->
        # <--- BODY starts here --->
        x("<body>")
        x("<p>This is a test.</p>")
        x("</body>")
        # <--- BODY ends here --->
        x("</html>")
        # <--- HTML ends here --->

if __name__ == '__main__':
    from BaseHTTPServer import HTTPServer
    server = HTTPServer(('localhost', 777), GetHandler)
    print 'Starting server, use <Ctrl + F2> to stop'
    server.serve_forever()

So in Python 3 you just need to change imports

from http.server import BaseHTTPRequestHandler

class GetHandler(BaseHTTPRequestHandler):

    def do_HEAD(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()

    def do_GET(self):
        x = self.wfile.write
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        # <--- HTML starts here --->
        x("<html>")
        # <--- HEAD starts here --->
        x("<head>")
        x("<title>Title goes here!</title>")
        x("</head>")
        # <--- HEAD ends here --->
        # <--- BODY starts here --->
        x("<body>")
        x("<p>This is a test.</p>")
        x("</body>")
        # <--- BODY ends here --->
        x("</html>")
        # <--- HTML ends here --->

if __name__ == '__main__':
    from http.server import HTTPServer
    server = HTTPServer(('localhost', 777), GetHandler)
    print('Starting server, use <Ctrl + F2> to stop')
    server.serve_forever()

9 Comments

Thanks @Tom-Oliver Heidel, Im a newbie, please guide me what to do with this code you have posted and where to place it to make my hello-world.py work oin the browser. Thanks
I cannot guarantuee 100% that the python3 code will work because I just used python docs in short time. But there is a tool called '2to3' which will convert python2 script into python3 script docs.python.org/2/glossary.html#term-to3 Actually you just need to copy the scripty and name it like e.g. 'httpserver.py' then you can use cmd and type in 'python httpserver.py' to start it.
I've changed 777 to 7777 (permission error on Unix) and replaced all str literals by bytes literals on Python 3. Ctrl + F2 does something unrelated on my Ubuntu machine. After that it shows: "This is a test." if you visit: localhost:7777.
@Yura when you got the file saved and executed with 'python filename.py' you can go and open your browser. type in 'localhost:777' or to whatever you changed the port in the script.
I never said to type in 'localhost:777/hello.py' when you executing the python file you can read 'Starting server ........' then you type into your browser 'localhost:777' nothing more.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.