当我将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第4版。这个问题基于示例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()
peoplecgi.py
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))
答案 0 :(得分:4)
在这种情况下的解决方案是我使用错误版本的Python来运行脚本。 osx 10.9中的默认值是Python 2.7.5。我想用python 3.3运行它,因此我的解决方案只是用适当的版本执行它:#!/usr/local/bin/python3