2012-12-19 50 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