簡體   English   中英

如何在 Python 中檢測 ftp 服務器超時

[英]How to detect ftp server timeouts in Python

將大量文件上傳到 FTP 服務器。 在我上傳的過程中,服務器超時,阻止我進一步上傳。 有誰知道檢測服務器是否超時、重新連接並繼續傳輸數據的方法? 我正在使用 Python ftp 庫進行傳輸。

謝謝

您可以簡單地為連接指定超時,但對於文件傳輸或其他操作期間的超時,它並不是那么簡單。

因為 storbinary 和 retrbinary 方法允許您提供回調,所以您可以實現看門狗定時器。 每次獲得數據時,您都會重置計時器。 如果您至少每 30 秒(或其他任何時間)未獲取數據,則看門狗將嘗試中止並關閉 FTP session 並將事件發送回您的事件循環(或其他)。

ftpc = FTP(myhost, 'ftp', 30)

def timeout():
  ftpc.abort()  # may not work according to docs
  ftpc.close()
  eventq.put('Abort event')  # or whatever

timerthread = [threading.Timer(30, timeout)]

def callback(data, *args, **kwargs):
  eventq.put(('Got data', data))  # or whatever
  if timerthread[0] is not None:
    timerthread[0].cancel()
  timerthread[0] = threading.Timer(30, timeout)
  timerthread[0].start()

timerthread[0].start()
ftpc.retrbinary('RETR %s' % (somefile,), callback)
timerthread[0].cancel()

如果這還不夠好,看來您將不得不選擇不同的 API。 Twisted 框架具有FTP 協議支持,應該允許您添加超時邏輯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM