Python SyntaxError:外部函数“返回”

时间:2018-07-30 16:02:37

标签: python

我刚刚将python从2升级到3,并开始出现以下错误。我也检查了缩进和空格,但没有运气

代码

var residents = [{name: "Pyrus", room: "32"},{name: "Ash Ketchum", room: "22"}];

residents.forEach(res => {
    Object.entries(res).forEach(([key, value]) => {
    console.log(key + ": " + value ); //subing console.log so it prints here
    //document.write(key + ": " + value + "<br>");
    })
})

错误

def _download_track(self, song_url, track_name, dir_name,metadata):
    if '.mp4' in song_url:
        track_name = track_name + '.m4a'
    else:
        track_name = track_name + '.mp3'        
    file_path = dir_name.replace(".","_") + '/' + track_name
    print(('Downloading to', file_path))
if os.path.isfile(file_path):
       return
    #print metadata
    #response = self._get_url_contents(song_url)
    #with open(file_path,'wb') as f:
    #f.write(response.content)
r = requests.get(song_url, stream=True, verify=False)
with open(file_path, 'wb') as f:
    for chunk in r.iter_content(chunk_size=1024): 
        if chunk:
            f.write(chunk)
            f.flush()
    if '.m4a' in track_name:
        self._update_metadata_mp4(file_path,metadata)
    else :
        self._update_metadata_mp3(file_path,metadata)

2 个答案:

答案 0 :(得分:0)

整个函数的代码必须缩进:

def _download_track(self, song_url, track_name, dir_name,metadata):
    if '.mp4' in song_url:
        track_name = track_name + '.m4a'
    else:
        track_name = track_name + '.mp3'        
    file_path = dir_name.replace(".","_") + '/' + track_name
    print(('Downloading to', file_path))
    if os.path.isfile(file_path):
        return
        #print metadata
        #response = self._get_url_contents(song_url)
        #with open(file_path,'wb') as f:
        #f.write(response.content)
    r = requests.get(song_url, stream=True, verify=False)
    with open(file_path, 'wb') as f:
        for chunk in r.iter_content(chunk_size=1024): 
            if chunk:
                f.write(chunk)
                f.flush()
        if '.m4a' in track_name:
            self._update_metadata_mp4(file_path,metadata)
        else :
            self._update_metadata_mp3(file_path,metadata)

答案 1 :(得分:0)

您的行:

if os.path.isfile(file_path):

不缩进,因此不在函数内。之后是“ return”,因此它也不在函数中。