This becomes a head scratching job and bit confusing too to configure web server to execute Python code. It's not rocket science but seems we get confused on googling and getting different suggestions. So we will provide here the perfect configuration to execute .py files in browser.
First of all open httpd.conf file from the \wamp\bin\apache\apachex.x.x\conf\ directory of your wamp directory. Search for the line <Directory "c:/wamp/www/"> (assuming that wamp is installed in C drive and your root directory is c:\wamp\www, you may also use any other root directory).
Uncomment these line if commented.
LoadModule cgi_module modules/mod_cgi.so
#LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so
Add this line if not exists.
Options +ExecCGI, if you are not sure what else to add, because by default all options are added if you do not mention them and adding any options restrict it to added options, unless you add one + sign before the option.
If "Options" line exists uncomment it if commented.
Add ExecCGI at the end.
Options Indexes FollowSymLinks ExecCGI.
Also add this line if does not exists
AddHandler cgi-script .cgi .py
Now put you python script in the root folder or some sub directory of root folder.
Do not forget to add this line at the begining of the script.
#!c:\pythonPath (i.e. #!c:\python34\python)
If you do not add this line script will not execute as browser will not know where is the python program to compile your script.
Now say your wamp base url is http://localhost:8090/ and your python script is in root directory. c:\wamp\www, then type http://localhost:8090/programName.py
Here is a sample program. This program will connect to the wamp server and display the welcome page.
#!D:/Python34/python
import socket
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server = 'localhost'
port = 8090
request = "GET / HTTP/1.1\r\nHost:" + server + ":" + str(port) + "\r\n\r\n"
s.connect((server, port))
s.send(request.encode('UTF-8'))
print("Content-Type: text/html\n\n")
result = "."
while len(result)>0:
result = s.recv(4096)
chunk = result.decode('UTF-8')
print(chunk)
#python #pythonprogramming #wamp #pythonscript
No comments:
Post a Comment