2012-12-19 53 views
3

这是我想赶上错误:Python中无法捕捉异常IndexError?

Traceback: 
    File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response 
     111.       response = callback(request, *callback_args, **callback_kwargs) 
    File "/opt/django/fileupload/views.py" in upload_file 
     56.   folder_info = url.split(':')[1] #Extracts folder info to use in the header 

    Exception Type: IndexError at /upload_file/ 
    Exception Value: list index out of range 

尝试使用:

except (socket.error, paramiko.AuthenticationException, IndexError): 
      return render_to_response('reform.html', context_instance=RequestContext(request)) 

但它不工作。

我能够赶上socket.errorparamiko.Authentication的例外,但不是IndexError。我正试图捕捉Django中的异常。谢谢。

编辑: 整个try和except块:

try:   
    source = str(username) + "@" + url #Source to list all the files 
    add_key = str(username) + "@" + test_url 
    add_known_hosts(password, add_key) #Add to the known hosts 
    test_ssh(test_url, username, password) #Test Host_name, username and password 
    destination = '/home/sachet/files'  
    command = subprocess.Popen(['sshpass', '-p', password, 'rsync', '--recursive', source], 
        stdout=subprocess.PIPE).communicate()[0] #sshpass needs to be installed into the server 
    lines = (x.strip() for x in command.split('\n')) 
    remote = [x.split(None, 4)[-1] for x in lines if x] #Removes permission from the file listing 
    base_name = [os.path.basename(ok) for ok in remote] 
    result = subprocess.Popen(['ls', destination], stdout=subprocess.PIPE).communicate()[0].splitlines() 

    return render_to_response('thanks.html', {'res1': remote, 'res': result, 'folder': folder_info}, context_instance=RequestContext(request)) 
except (socket.error, paramiko.AuthenticationException, IndexError): 
    return render_to_response('reform.html', context_instance=RequestContext(request)) 
+2

您能否提供产生追溯的完整代码?你的'except'块看起来是正确的。 –

+0

发布整个'try-except'块。 – Aesthete

+0

是什么版本的Python? – Keith

回答

1

的IndexError没有在尝试中引发了/ except块您发布。 IndexError在folder_info被分配到的行上引发(view.py中的第56行)。您需要将该行代码移入try/except块以捕获该错误。

File "/opt/django/fileupload/views.py" in upload_file 
    56.   folder_info = url.split(':')[1] <-- This line 

或者,更好的是,把一个单独的try /除了围绕“文件夹= ...”行,只是为了IndexError,使你的代码的意图更加清晰。

+0

这就是我所缺少的。谢谢 – user1881957