我在使用 paramiko 库时遇到问题,特别是与 SFTPClient 模块有关的问题。我试图从目录中递归下载文件,包括所有子目录及其内容。但是,我很难确定给定路径是否是 SFTPClient 中的目录。
我正在使用最新版本的paramiko(版本3.4.0)。以下是我的 Python 代码的相关部分:
def download_files(self, local_dir):
if self.sftp_instance:
current_dir = self.sftp_instance.getcwd()
local_path = os.path.join(local_dir, os.path.basename(current_dir))
os.makedirs(local_path, exist_ok=True)
files = self.get_list_of_files_in_current_dir()
for item in files:
remote_path = os.path.join(current_dir, item)
item_local_path = os.path.join(local_path, item)
print("Remote path:", remote_path)
print("cwd", self.sftp_instance.getcwd())
print("Is directory:", self.sftp_instance.stat(item).st_isdir()) # This line raises an AttributeError
if self.sftp_instance.stat(remote_path).isdir(): # This is where I'm experiencing issues
if not self.sftp_instance.listdir(remote_path):
print(f"Skipped empty directory: {item}")
else:
self.sftp_instance.chdir(remote_path)
self.download_files(local_path)
self.sftp_instance.chdir("..")
else:
try:
self.sftp_instance.get(remote_path, item_local_path)
print(f"Downloaded file: {item}")
except IOError as e:
print(f"Error downloading file: {item}")
print(f"Error message: {str(e)}")
print(f"Error details:")
print(f" errno: {e.errno}")
print(f" strerror: {e.strerror}")
print(f" filename: {e.filename}")
except Exception as e:
print(f"Error downloading file: {item}. {str(e)}")
else:
print("SFTP connection not established. Please connect first.")
造成问题的具体线路是:
print("Is directory:", self.sftp_instance.stat(item).st_isdir())
此行引发以下错误:
AttributeError: 'SFTPAttributes' object has no attribute 'st_isdir'
我还尝试直接在 self.sftp_instance.stat(remote_path) 返回的 SFTPAttributes 对象上使用 isdir() 方法,但似乎该方法不可用。
paramiko 库是否提供了不同的方法或方法,我应该使用它来确定给定路径是否是目录?任何见解或替代方案将不胜感激。谢谢你。
对于
stat()
函数调用,返回值是一个对象,其属性对应于os.stat
返回的Python stat结构的属性。
这意味着你可以做
import stat
print("Is directory:", stat. S_ISDIR(self.sftp_instance.stat(item).st_mode))