Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run CGI "hello world" with python http.server

Tags:

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?

like image 849
Yura Avatar asked May 28 '15 20:05

Yura


1 Answers

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.

like image 189
jfs Avatar answered Sep 28 '22 03:09

jfs