当我将http:// localhost:8888 / cgi-bin / peoplecgi.py?action = Fetch& key = sue(sue是货架上的有效密钥)发送到下面的cgi脚本时,我得到了以下内容(也是在使用Python 3.3的OSX上).任何想法出了什么问题?
127.0.0.1 - - [04/Feb/2014 10:38:41] "GET /cgi-bin/peoplecgi.py?action=Fetch&key=sue HTTP/1.1" 200 -
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/http/server.py", line 1131, in run_cgi
os.execve(scriptfile, args, env)
OSError: [Errno 8] Exec format error: '/Users/rich/Google Drive/Code/Python/PP4E/Preview/cgi-bin/peoplecgi.py'
127.0.0.1 - - [04/Feb/2014 10:38:41] CGI script exit status 0x7f00
我正在研究O’Reilly的Programming Python 4th Edition.这是基于示例1-33的问题.
weberver.py:
import os, sys
from http.server import HTTPServer, CGIHTTPRequestHandler
webdir = '/Users/rich/Google Drive/Code/Python/PP4E/Preview/'
port = 8888
os.chdir(webdir)
srvraddr = ("", port)
srvrobj = HTTPServer(srvraddr, CGIHTTPRequestHandler)
srvrobj.serve_forever()
人民网
import cgi, shelve, sys, os
shelvename = 'class-shelve'
fieldnames = ('name', 'age', 'job', 'pay')
form = cgi.FieldStorage()
print('Content-type: text/html')
sys.path.insert(0, os.getcwd())
replyhtml="""
<html>
<title>People Input Form</title>
<body>
<form method=POST action="peoplecgi.py">
<table>
<tr><th>key<td><input type=text name=key value="%(key)s">
$ROWS$
</table>
<p>
<input type=submit value="Fetch", name=action>
<input type=submit value="Update", name=action>
</form>
</body></html>
"""
rowhtml = '<tr><th>%s<td><input type=text name=%s value="%%(%s)s">\n'
rowshtml = ''
for fieldname in fieldnames:
rowshtml += (rowhtml % ((fieldname,) * 3))
replyhtml = replyhtml.replace('$ROWS$', rowshtml)
def htmlize(adict):
new = adict.copy()
for field in fieldnames:
value = new[field]
new[field] = cgi.escape(repr(value))
return new
def fetchRecord(db, form):
try:
key = form['key'].value
record = db[key]
fields = record.__dict__
fields['key'] = key
except:
fields = dict.fromkeys(fieldnames, '?')
fields['key'] = 'Missing or invalid key!'
return fields
def updateRecord(db, form):
if not 'key' in form:
fields = dict.fromkeys(fieldnames, '?')
fields['key'] = 'Missing key input!'
else:
key = form['key'].value
if key in db:
record = db[key]
else:
from person import Person
record = Persion(name='?', age='?')
for field in fieldnames:
setattr(record, field, eval(form[field].value))
db[key] = record
fields = record.__dict__
fields['key'] = key
return fields
db = shelve.open(shelvename)
action = form['action'].value if 'action' in form else None
if action == 'Fetch':
fields = updateRecord(db, form)
else:
fields = dict.fromkeys(fieldnames, '?')
fields['key'] = 'Missing or invalid action!'
db.close()
print(replyhtml % htmlize(fields))
解决方法:
在这种情况下,解决方案是我使用了错误版本的Python运行脚本. osx 10.9中的默认值是Python 2.7.5.我想使用python 3.3来运行它,因此我的解决方案只是简单地使用适当的版本执行它:#!/usr/local/bin / python3