Python pysftp put_r在Windows上不起作用 [英] Python pysftp put_r does not work on Windows
问题描述
我想使用pysftp 0.2.8从Windows目录上载多个文件到SFTP服务器.我已阅读文档,并建议使用put_d
或put_r
,但都给我以下错误:
I'd like to upload multiple files from a Windows directory to an SFTP server using pysftp 0.2.8. I've read up the doc and it suggests to use put_d
or put_r
but both give me the following error:
OSError:无效的路径:
OSError: Invalid path:
sftp_local_path = r'C:\Users\Swiss\some\path'
sftp_remote_path = '/FTP/LPS Data/ATC/RAND/20191019_RAND/XML'
with pysftp.Connection("xxx.xxx.xxx.xxx", username=myUsername, password=myPassword) as sftp:
with sftp.cd(sftp_remote_path):
sftp.put_r(sftp_local_path, sftp_remote_path)
for i in sftp.listdir():
lstatout=str(sftp.lstat(i)).split()[0]
if 'd' in lstatout: print (i, 'is a directory')
sftp.close()
我希望能够将所有文件或所选文件从本地目录复制到SFTP服务器.
I'd like to be able to copy all files or selected files from my local directory to the SFTP server.
推荐答案
我无法重现您的确切问题,但是确实已知pysftp的递归函数的实现方式使它们在Windows(或任何不使用类似* nix的路径语法.
I cannot reproduce your exact problem, but indeed the recursive functions of pysftp are known to be implemented in a way that makes them fail on Windows (or any system that does not use *nix-like path syntax).
它对远程SFTP路径使用os.sep
和os.path
函数,这是错误的,因为SFTP路径始终使用正斜杠.
It uses os.sep
and os.path
functions for remote SFTP paths, what is wrong, as SFTP paths always use a forward slash.
但是您可以轻松实现便携式替换:
But you can easily implement a portable replacement:
import os
def put_r_portable(sftp, localdir, remotedir, preserve_mtime=False):
for entry in os.listdir(localdir):
remotepath = remotedir + "/" + entry
localpath = os.path.join(localdir, entry)
if not os.path.isfile(localpath):
try:
sftp.mkdir(remotepath)
except OSError:
pass
put_r_portable(sftp, localpath, remotepath, preserve_mtime)
else:
sftp.put(localpath, remotepath, preserve_mtime=preserve_mtime)
使用方式如下:
put_r_portable(sftp, sftp_local_path, sftp_remote_path, preserve_mtime=False)
有关get_r
的类似问题,请参见:
来自Linux的Python pysftp get_r在Linux上运行良好,但在Windows上却无法运行
For a similar question about get_r
, see:
Python pysftp get_r from Linux works fine on Linux but not on Windows
这篇关于Python pysftp put_r在Windows上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!