ftplib 超时

ftplib is timing out

我正在尝试将 5 个文件发送到 ftp 服务器。但是,5个文件中只发送了前3个,而没有发送后2个。

我怀疑这与超时有关,但我不确定,因为传输前 3 个文件大约需要 5 分钟。

有什么建议吗?

##旧代码

import subprocess

#ftp credentials
server='myserver.host.com'
user='admin@mywebsite.com'
password='mypassword'

#logging in to ftp
proc =subprocess.Popen(['ftp -p {}'.format(server)],shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
#sending username
proc.stdin.write(bytes(user+'\n',encoding='UTF-8'))
proc.stdin.flush()
#sending password
proc.stdin.write(bytes(password+'\n',encoding='UTF-8'))
proc.stdin.flush()

#name of ftp directory were files will be transferred
ftpdirectory='ftpdir'

#list of file directories to be transferred 
filestotransfer=['/home/user/Desktop/file1.csv','/home/user/Desktop/file2.csv','/home/user/Desktop/file3.csv','/home/user/Desktop/file4.csv','/home/user/Desktop/file5.csv']

#transferring files one by one
for i in filestotransfer:
    filename=i.split('/')[-1]
    syntaxx='put "{}" "/{}/{}"'.format(i,ftpdirectory,filename) #put /home/user/Desktop/file1.csv /ftpdir/file1.csv
    proc.stdin.write(bytes(syntaxx + '\n', encoding='UTF-8'))
    proc.stdin.flush()

##解决方案

import ftplib
import os.path


server = "myserver.host.com"
user = "admin@mywebsite.com"
password = "mypassword"
ftpdirectory = "/ftpdir"

filestotransfer = [
    "/home/user/Desktop/file1.csv",
    "/home/user/Desktop/file2.csv",
    "/home/user/Desktop/file3.csv",
    "/home/user/Desktop/file4.csv",
    "/home/user/Desktop/file5.csv",
]
for i in filestotransfer:
    try:
        with ftplib.FTP(server,timeout=10) as ftp:
            print('logging in')
            ftp.login(user, password)
    
    
            with open(i, "rb") as fp:
                dest_path = os.path.join(ftpdirectory, os.path.basename(i))
                ftp.storbinary(f"STOR {dest_path}", fp)
                print('completed sending {}'.format(i))
    
            ftp.close()
            
            
    except:
        print('timedout')
        

正如我在评论中提到的,ftplib 是 Python 中的一个 built-in 模块。

您的脚本简化为类似

import ftplib
import os.path
import posixpath

server = "myserver.host.com"
user = "admin@mywebsite.com"
password = "mypassword"
ftpdirectory = "/ftpdir"
filestotransfer = [
    "/home/user/Desktop/file1.csv",
    "/home/user/Desktop/file2.csv",
    "/home/user/Desktop/file3.csv",
    "/home/user/Desktop/file4.csv",
    "/home/user/Desktop/file5.csv",
]

with ftplib.FTP(server) as ftp:
    ftp.login(user, password)
    for filepath in filestotransfer:
        with open(filepath, "rb") as fp:
            dest_path = posixpath.join(ftpdirectory, os.path.basename(filepath))
            print(f"Transferring {filepath} to {dest_path}")
            ftp.storbinary(f"STOR {dest_path}", fp)