我正在使用popen
从PHP窗口运行Python脚本。在Python脚本中,我运行urllib.urlopen
。从Internet Explorer,Safari和Firefox运行PHP时,urllib.urlopen
始终会抛出此错误:
Error: ['Traceback (most recent call last):', ' File "/home4/pantano/public_html/software/eco/python/query.py", line 29, in geocode\n data = eval(urlopen(url).read())\n', ' File "", line 148, in \n', "NameError: name 'true' is not defined\n"].
#straight from traceback module
此从不在Google Chrome中发生,我使用的是有效网址。
我怀疑这会有所帮助,但这里使用的是Python,包含在query.py
:
def geocode(self, address, console, num, outof, attempt):
'''Returns LatLng of Geocoding API'''
if attempt == self.max_failed_queries:
console.add('elevation', num, outof, False, 'Quitting this query. Data will be inaccurate')
return None, False
url = 'https://maps.googleapis.com/maps/api/geocode/json?address='+address.replace(' ','+',len(address))+'&key=AIzaSyCnHT7IpJu0O7n-apLNW8iKkW_rTIuANuE'
current_time = time.time()
if current_time < self.next_query_time: #before earliest possible query time
time.sleep(self.next_query_time - current_time) #wait until next query time
try:
data = eval(urlopen(url).read())
self.next_query_time = current_time + 0.2
if data['status'] == 'OK':
console.add('geocode', num, outof)
return LatLng(float(data['results'][0]['geometry']['location']['lat']), float(data['results'][0]['geometry']['location']['lng'])), True
else:
console.add('geocode', num, outof, False, 'Problem with query or data: '+data['status'])
return self.geocode(address, console, num, outof, attempt+1)
except:
type_, value_, traceback_ = sys.exc_info()
console.add('geocode', num, outof, False, str(traceback.format_exception(type_, value_, traceback_)))
return self.geocode(address, console, num, outof, attempt+1)
该网站托管在远程HostGator服务器上。
有人可以解释为什么会发生这种情况并为此提供解决方法吗?
答案 0 :(得分:0)
如果您从API请求json
,则不应该eval
它,它会将其作为Python代码处理。相反,你应该加载json:
import json
data = json.load(urlopen(url))
目前您的问题即将到来,因为JSON中有true
,这是有效的JSON,但不是有效的Python:在Python中,布尔值为True
(请注意大写{ {1}})。
一般来说,对于T
来说,这是一个可怕,可怕,可怕的想法。当你不控制源头时更是如此。