简体   繁体   English

检查Python FTP连接

[英]Checking a Python FTP connection

I have a FTP connection from which I am downloading many files and processing them in between. 我有一个FTP连接,我从中下载许多文件并在其间处理它们。 I'd like to be able to check that my FTP connection hasn't timed out in between. 我希望能够检查我的FTP连接之间没有超时。 So the code looks something like: 所以代码看起来像:

conn = FTP(host='blah')
conn.connect()
for item in list_of_items:
    myfile = open('filename', 'w')
    conn.retrbinary('stuff", myfile)
    ### do some parsing ###

How can I check my FTP connection in case it timed out during the ### do some parsing ### line? 如何在### do some parsing ###行时超时的情况下检查我的FTP连接?

Send a NOOP command. 发送NOOP命令。 This does nothing but check that the connection is still going and if you do it periodically it can keep the connection alive. 这只会检查连接是否仍在继续,如果你定期这样做,它可以使连接保持活动状态。

For example: 例如:

   conn.voidcmd("NOOP")

If there is a problem with the connection then the FTP object will throw an exception. 如果连接出现问题,则FTP对象将抛出异常。 You can see from the documentation that exceptions are thrown if there is an error: 您可以从文档中看到,如果出现错误,则会抛出异常:

socket.error and IOError: These are raised by the socket connection and are most likely the ones you are interested in. socket.error和IOError:这些是由套接字连接引发的,很可能是你感兴趣的。

exception ftplib.error_reply: Exception raised when an unexpected reply is received from the server. exception ftplib.error_reply:从服务器收到意外回复时引发的异常。

exception ftplib.error_temp: Exception raised when an error code signifying a temporary error (response codes in the range 400–499) is received. exception ftplib.error_temp:当收到表示临时错误的错误代码(响应代码在400-499范围内)时引发异常。

exception ftplib.error_perm: Exception raised when an error code signifying a permanent error (response codes in the range 500–599) is received. exception ftplib.error_perm:当收到表示永久性错误的错误代码(响应代码在500-599范围内)时引发异常。

exception ftplib.error_proto: Exception raised when a reply is received from the server that does not fit the response specifications of the File Transfer Protocol, ie begin with a digit in the range 1–5. exception ftplib.error_proto:从服务器收到不符合文件传输协议响应规范的回复时引发的异常,即以1-5范围内的数字开头。

Therefore you can use a try-catch block to detect the error and handle it accordingly. 因此,您可以使用try-catch块来检测错误并相应地处理它。

For example this sample of code will catch an IOError, tell you about it and then retry the operation: 例如,此代码示例将捕获IOError,告诉您它,然后重试该操作:

retry = True
while (retry):
    try:
        conn = FTP('blah')
        conn.connect()
        for item in list_of_items:
            myfile = open('filename', 'w')
            conn.retrbinary('stuff', myfile)   
            ### do some parsing ###

        retry = False

    except IOError as e:
        print "I/O error({0}): {1}".format(e.errno, e.strerror)
        print "Retrying..."
        retry = True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM