2016-06-21 64 views
0

嘗試從另一個函數內的某個函數訪問變量時,我總是收到以下錯誤。無法訪問函數以外的變量

NameError:全局名稱「savemovieurl」沒有定義

我怎樣才能訪問「savemovieurl」從功能「tmdb_posters」內部「dynamic_data_entry」將其保存到數據庫?

我試着給變量名添加全局變量,但沒有成功。

import requests 
import urllib 

import sqlite3 
import time 
import datetime 
import random 



movie = raw_input('Enter your movie: ') 
print('You searched for: ', movie) 

def imdb_id_from_title(title): 
    """ return IMDb movie id for search string 

     Args:: 
      title (str): the movie title search string 
     Returns: 
      str. IMDB id, e.g., 'tt0095016' 
      None. If no match was found 
    """ 
    pattern = 'http://www.imdb.com/xml/find?json=1&nr=1&tt=on&q={movie_title}' 
    url = pattern.format(movie_title=urllib.quote(title)) 
    r = requests.get(url) 
    res = r.json() 
    # sections in descending order or preference 
    for section in ['popular','exact','substring']: 
     key = 'title_' + section 
     if key in res: 
      return res[key][0]['id'] 

if __name__=="__main__": 
    title = movie 
    imdb_info_returned = ("{1}".format(title, imdb_id_from_title(title))) 
    print imdb_info_returned 


import os 
import requests 

CONFIG_PATTERN = 'http://api.themoviedb.org/3/configuration?api_key={key}' 
IMG_PATTERN = 'http://api.themoviedb.org/3/movie/{imdbid}/images?api_key={key}' 
KEY = '47db65094c31430c5a2b65112088d70e' 

imdb_id_input = imdb_info_returned 
print('You searched for: ', imdb_id_input) 



def _get_json(url): 
    r = requests.get(url) 
    return r.json() 

def _download_images(urls, path='.'): 
    """download all images in list 'urls' to 'path' """ 

    for nr, url in enumerate(urls): 
     r = requests.get(url) 
     filetype = r.headers['content-type'].split('/')[-1] 
     filename = 'poster_{0}.{1}'.format(nr+1,filetype) 
     filepath = os.path.join(path, filename) 
     with open(filepath,'wb') as w: 
      w.write(r.content) 

def get_poster_urls(imdbid): 
    """ return image urls of posters for IMDB id 
     returns all poster images from 'themoviedb.org'. Uses the 
     maximum available size. 
     Args: 
      imdbid (str): IMDB id of the movie 
     Returns: 
      list: list of urls to the images 
    """ 
    config = _get_json(CONFIG_PATTERN.format(key=KEY)) 
    base_url = config['images']['base_url'] 
    sizes = config['images']['poster_sizes'] 

    """ 
     'sizes' should be sorted in ascending order, so 
      max_size = sizes[-1] 
     should get the largest size as well.   
    """ 
    def size_str_to_int(x): 
     return float("inf") if x == 'original' else int(x[1:]) 
    max_size = max(sizes, key=size_str_to_int) 

    posters = _get_json(IMG_PATTERN.format(key=KEY,imdbid=imdbid))['posters'] 
    poster_urls = [] 


    rel_path = posters[0]['file_path'] 
    url = "{0}{1}{2}".format(base_url, max_size, rel_path) 
    poster_urls.append(url) 

    return poster_urls 

def tmdb_posters(imdbid, count=None, outpath='.'):  
    urls = get_poster_urls(imdbid) 
    if count is not None: 
     urls = urls[:count] 
    _download_images(urls, outpath) 




    savemovieurl = urls 
    print savemovieurl 





conn = sqlite3.connect('tutorial.db') 
c = conn.cursor() 



def create_table(): 
    c.execute("CREATE TABLE IF NOT EXISTS movies(unix REAL, datestamp TEXT, keyword TEXT, value REAL, moviename TEXT, movieimage TEXT, movieurl TEXT)") 

def data_entry(): 
    c.execute("INSERT INTO movies VALUES(1452549219,'2016-01-11 13:53:39','Python',6,'movienamehere1', 'savemovieurl', 'movieurlhere1')") 
    conn.commit() 
    c.close() 
    conn.close() 



def dynamic_data_entry(argument) : 
    unix = time.time() 
    date = str(datetime.datetime.fromtimestamp(unix).strftime('%Y-%m-%d %H: %M: %S')) 
    keyword = 'keyword_string' 
    movieurl = 'bing.com' 
    value = random.randrange(0,10) 
    savemovieurl2 = 'testimageurl.com' 
    print argument 
    c.execute("INSERT INTO movies (unix, datestamp, keyword, value, moviename, movieimage, movieurl) VALUES (?, ?, ?, ?, ?, ?, ?)", (unix, date, keyword, value, movie, savemovieurl2, movieurl)) 
    conn.commit() 

create_table() 
#data_entry() 

for i in range(10) : 
    dynamic_data_entry(savemovieurl) 
    time.sleep(1) 
c.close() 
conn.close() 



if __name__=="__main__": 
    tmdb_posters(imdb_id_input) 
+3

您是否熟悉關鍵字'return'?不要*用函數打印*值 - *返回*,以便調用代碼可以使用它們或將它們傳遞給它們。 –

+0

所以如果我用返回替換打印它應該工作? – Hunter

+0

@JohnColeman和Sofia都是正確的,你的問題的答案是使用'return'語句。 **然而**,看着你的代碼,我不相信答案真的有幫助。您已經創建了兩個獨立運行的文件,並將它們串聯在一起:這可能有時會起作用,但最終將導致長期無法挽回的情況。我並不是說聽起來很居高臨下,但你真正需要的是Python基礎教程:如何運行python腳本,什麼是函數,爲什麼是'if __name__ =='__main __「:'there,e​​tc –

回答

0

我覺得這已經在這裏找到答案:How do I use a variable so that it is inside and outside of a function

我知道我應該出於某種原因,我不能,所以我只是想我會寫一個答案,而不是然而這個評論。我希望這有幫助。

+0

我還不清楚該怎麼辦? – Hunter

+0

爲函數(dynamic_data_entry),我傳遞從tmdb_posters返回的值作爲函數的參數。然而,我可以打印沒有錯誤的打印功能的參數,但是當我嘗試將參數保存到一個變量用於保存在數據庫中時,我收到一個錯誤。 爲什麼我可以打印參數,但不保存到變量? – Hunter