2015-06-24 43 views
0

我使用popen從PHP窗口運行Python腳本。在Python腳本中,我運行urllib.urlopen。當PHP是從Internet Explorer,Safari瀏覽器和Firefox上運行,這個錯誤總是被urllib.urlopen拋出:Python urllib.urlopen NameError:通過PHP從命令行運行

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 

從未發生在谷歌Chrome和我使用的是有效的URL。

我懷疑這會有所幫助,但這裏是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

如果您從API請求json,則不應該使用eval它將其作爲Python代碼進行處理。相反,你應該加載JSON:

import json 
data = json.load(urlopen(url)) 

目前您的問題來了,因爲有一個在JSON,這是有效的JSON,但不是有效的Python中的true:Python中,布爾值true是True(注意是大寫T)。


一般來說,這是一個可怕的,可怕的,可怕的想法eval東西。當你不控制源時更是如此。

+0

但爲什麼在Google Chrome中不會發生這種情況? – bcdan

+0

@bcdan您沒有足夠的代碼發佈在這裏,我可以回答這個問題。 –