Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python ftplib,如何在没有errno属性的情况下管理异常?_Python_Exception_Python 2.7_Ftplib - Fatal编程技术网

Python ftplib,如何在没有errno属性的情况下管理异常?

Python ftplib,如何在没有errno属性的情况下管理异常?,python,exception,python-2.7,ftplib,Python,Exception,Python 2.7,Ftplib,如果文件不存在,我想在ftp站点上传文件。这是一个更复杂的应用程序的任务,但在这种情况下并不重要。 我的想法是用FTP.size(filename)方法检查文件是否存在,如果错误为550(系统找不到指定的文件),则上载文件 我的(不工作)代码: 返回的错误是 Traceback (most recent call last): File "<pyshell#106>", line 4, in <module> if e.errno == 550: Attrib

如果文件不存在,我想在ftp站点上传文件。这是一个更复杂的应用程序的任务,但在这种情况下并不重要。 我的想法是用
FTP.size(filename)
方法检查文件是否存在,如果错误为550(系统找不到指定的文件),则上载文件

我的(不工作)代码:

返回的错误是

Traceback (most recent call last):
  File "<pyshell#106>", line 4, in <module>
    if e.errno == 550:
AttributeError: 'error_perm' object has no attribute 'errno'
我找到的唯一管理返回代码的解决方案是:

except ftplib.all_errors, e:
if str(e.args[0]).split(" ", 1)[0] == "550":
        print "UPLOAD"
    else:
        print str(e)
但我认为有一个最好的解决方案,因为只有当错误号是异常消息中的第一个字时,这才有效


提前谢谢你

我不知道该错误的确切属性,所以您可以在except子句激活时打印dir(e)。然后您将看到错误的所有属性。一个几乎从不失败的标志是“error.message”,它是一个字符串,因此您可以用它来构建if子句

你会以这样的方式结束

try:
    ftp.size("123.zip")
except ftplib.all_errors as e:
    if e.message == 'message of the error'
        print 'UPLOAD'
    else:
        print str(e)

顺便说一句,当执行str(e)时,您会得到一条消息。

也许这有帮助,它来自ftplib的文档

请注意,SIZE命令不是标准化的,但是许多常见的服务器实现都支持它

链接


尝试使用另一种方法来确定文件是否存在。

此代码在我的计算机上运行正常。您确定使用的是正确的Python版本吗?我在跑2.7。
except ftplib.all_errors, e:
if str(e.args[0]).split(" ", 1)[0] == "550":
        print "UPLOAD"
    else:
        print str(e)
try:
    ftp.size("123.zip")
except ftplib.all_errors as e:
    if e.message == 'message of the error'
        print 'UPLOAD'
    else:
        print str(e)