Python try/except不起作用 [英] Python try/except not working

查看:1078
本文介绍了Python try/except不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图使try/except语句正常工作,但出现问题.此代码将获取一个txt文件,并将位置行0中的文件复制到行1中的位置.它可以工作,但是如果我将其中一个路径更改为无效路径,则会生成错误ftplib.error_perm,但是除外命令未选择起来,一切都停止了.我究竟做错了什么? Python 2.4

Trying to get the try/except statement working but having problems. This code will take a txt file and copy the file that is in location row 0 to location of row 1. It works however if i change one of the paths to invalid one it generates an error ftplib.error_perm however the except command is not picking up and everything stops. What am i doing wrong? Python 2.4

import csv
import operator
import sys
import os
import shutil
import logging
import ftplib
import tldftp

def docopy(filename):
        ftp = tldftp.dev()
        inf = csv.reader(open(filename,'r'))
        sortedlist = sorted(inf, key=operator.itemgetter(2), reverse=True)
        for row in sortedlist:
                src = row[0]
                dst = row[1]
                tldftp.textXfer(ftp, "RETR " + src, dst)


def hmm(haha):
    result = docopy(haha);
    try:
        it = iter(result)
    except ftplib.error_perm:
        print "Error Getting File" 


if __name__ == "__main__":
        c = sys.argv[1]
        if (c == ''):
                raise Exception, "missing first parameter - row"
        hmm(c)

推荐答案

except子句将仅捕获在相应try块内raise d的异常.尝试将docopy函数调用也放入try块内:

The except clause will only catch exceptions that are raised inside of their corresponding try block. Try putting the docopy function call inside of the try block as well:

def hmm(haha):
    try:
        result = docopy(haha)
        it = iter(result)
    except ftplib.error_perm:
        print "Error Getting File" 

这篇关于Python try/except不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆