You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让pysftp的conn.stat方法在目标文件不存在时抛出错误

问题原因
  • 你的现有逻辑仅在存在符合fnmatch_pattern匹配规则的文件时,才会进入for循环调用conn.stat方法。当匹配结果flist为空时,循环体完全不会执行,自然不会触发conn.stat找不到文件时抛出的IOError。
  • 额外注意:SFTP路径统一使用正斜杠(/)拼接,不要用os.path.join,该方法会根据本地操作系统生成路径分隔符,Windows环境下会生成反斜杠,导致SFTP服务端识别路径错误。
解决方案

你可以在生成匹配文件列表后主动校验列表长度,为空时手动抛出和conn.stat行为一致的异常即可,修改后代码如下:

from typing import Dict
import pysftp
import fnmatch

def get_mod_time_pattern(self, dir_path: str, fnmatch_pattern: str = None) -> Dict[str, str]:
    d = {}
    conn = pysftp.Connection(**my_conn_paramt)
    
    # 筛选符合匹配规则的文件列表
    flist = [file for file in conn.listdir(dir_path) if fnmatch.fnmatch(file, fnmatch_pattern)]
    
    # 无匹配文件时主动抛出对应异常
    if not flist:
        # 抛出和conn.stat找不到文件时一致的IOError,错误信息参考pysftp原生报错
        raise IOError(f"[Errno 2] No such file or directory: matching pattern {fnmatch_pattern} under {dir_path}")

    for file in flist:
        # 用正斜杠拼接SFTP路径,避免os.path.join的跨平台问题
        path_to_file = f"{dir_path.rstrip('/')}/{file}"
        d[path_to_file] = conn.stat(path_to_file).st_mtime

    return d

注意:conn.stat().st_mtime返回的是浮点型时间戳,如果你需要字符串格式的修改时间,需要额外调用datetime类的方法做格式转换,否则和你函数标注的Dict[str, str]返回类型会不匹配。

如果需要完全对齐conn.stat的原生报错格式,也可以在无匹配时直接调用一次conn.stat传入你预期的目标路径,触发原生的错误抛出逻辑。

内容的提问来源于stack exchange,提问作者Saverio Guzzo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 01:30:01