python中的递归方法

时间:2015-06-06 09:54:03

标签: python sockets python-2.7 file-upload ftp

我正在尝试通过ftp将csv文件发送到远程服务器,但有时我会收到套接字错误:

现在我想使功能恢复,以便如果函数无法通过ftp发送文件,它应该再试一次。这就是我正在做的事情,即使第一次尝试连接失败,我怎样才能成功上传文件。

    def upload(ftp,file_path):
        os.chdir(file_path)
        files=glob.glob('*.csv')
        for filename in files:
            print filename
            ftp.storbinary("STOR " + filename, open(filename, "rb"), 1024)
            time.sleep(1)

   ftp=FTP(ftp_server)
   ftp.login(ftp_user,ftp_password)
   ftp.cwd("/test")

   file_path='/test'
   upload(ftp,file_path)

我收到以下错误:

追踪(最近一次呼叫最后一次):

  File "file_upload.py", line 205, in <module>
    upload(ftp,file_path)
  File "file_upload.py", line 105, in upload
    ftp.storbinary("STOR " + filename, open(filename, "rb"), 1024)
  File "/usr/lib/python2.7/ftplib.py", line 470, in storbinary
    self.voidcmd('TYPE I')
  File "/usr/lib/python2.7/ftplib.py", line 253, in voidcmd
    self.putcmd(cmd)
  File "/usr/lib/python2.7/ftplib.py", line 181, in putcmd
    self.putline(line)
  File "/usr/lib/python2.7/ftplib.py", line 176, in putline
    self.sock.sendall(line)
  File "/usr/lib/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 104] Connection reset by peer

1 个答案:

答案 0 :(得分:2)

使用try / except捕获套接字错误:

from socket import error

for filename in files:
        try:
            print filename
            ftp.storbinary("STOR " + filename, open(filename, "rb"), 1024)
            time.sleep(1)
        except error as e:
            print(e)

如果您想多次重试,请使用内部循环,如果调用成功则中断,或者重试n次:

  for filename in files:
        for ty in range(n):
            try:
                print filename
                ftp.storbinary("STOR " + filename, open(filename, "rb"), 1024)
                time.sleep(1)
                break
            except error as e:
                print(e)

您可以将n传递给您的函数以决定您想要的重试次数:

def upload(ftp, file_path, n):
    os.chdir(file_path)
    files = glob.glob('*.csv')
    for filename in files:
        for ty in range(n):
            try:
                print filename
                # with will close your file
                with open(filename, "rb") as f:
                    ftp.storbinary("STOR {}".format(filename), f, 1024)
                time.sleep(1)
                break
            except error as e:
                print(e)

您可以使用while True循环,但这可能会永远循环