Python ftplib OSError: [WinError 10013] on STOR operation

Python ftplib OSError: [WinError 10013] on STOR operation

我有一个 python3 程序正在使用 ftplib 上传大量文件。

它工作正常,但偶尔会在上传的随机点抛出以下异常:

[WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions
Traceback (most recent call last):
  File "bulk_box_ftp.py", line 90, in push_folder_contents
    placeFiles(ftp_conn, folder)
  File "bulk_box_ftp.py", line 68, in placeFiles
    placeFiles(ftp, localpath)
  File "bulk_box_ftp.py", line 52, in placeFiles
    ftp.storbinary('STOR ' + name, upfile)
  File "...\Python\Python36-32\lib\ftplib.py", line 503, in storbinary
    self.voidcmd('TYPE I')
  File "...\Python\Python36-32\lib\ftplib.py", line 278, in voidcmd
    return self.voidresp()
  File "...\Python\Python36-32\lib\ftplib.py", line 251, in voidresp
    resp = self.getresp()
  File "...\Python\Python36-32\lib\ftplib.py", line 236, in getresp
    resp = self.getmultiline()
  File "...\Programs\Python\Python36-32\lib\ftplib.py", line 222, in getmultiline
    line = self.getline()
  File "...\Python\Python36-32\lib\ftplib.py", line 204, in getline
    line = self.file.readline(self.maxline + 1)
  File "...\Python\Python36-32\lib\socket.py", line 586, in readinto
    return self._sock.recv_into(b)
  File "...\Python\Python36-32\lib\ssl.py", line 1009, in recv_into
    return self.read(nbytes, buffer)
  File "...\Python\Python36-32\lib\ssl.py", line 871, in read
    return self._sslobj.read(len, buffer)
  File "...\Python\Python36-32\lib\ssl.py", line 631, in read
    v = self._sslobj.read(len, buffer)
OSError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions

在此之后 OSError 队列中的所有其他文件将抛出 ConnectionResetError

ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

什么可能导致引发此异常?有什么方法可以安全地捕获它并恢复以继续 FTP 操作?

经过反复试验,我发现 FTP 连接必须执行完全重置。我将所有 FTP 上传代码包装在一个 try: 块中,并在引发 OSError 时捕获:

except OSError as e:
  print("FTP Connection Error Occurred")
  attempt_conn_reset(current_pwd)

并且此函数将终止 re-establish FTP 连接:

def attempt_conn_reset(pwd="/"):
  # resets the FTP connection in case of a socket disconnect
  print("Attempting FTP reconnect")
  try:
      ftp_conn.quit()
  except ConnectionResetError:
    print("Connection was already closed")
  # allow OS to release port
  time.sleep(2)
  ftp_conn.connect(FTP_URL)
  ftp_conn.login(FTP_USER, FTP_PASSWORD)
  ftp_conn.prot_p()
  ftp_conn.cwd(pwd)
  print("FTP connection has been reset")