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

Python使用subprocess.run执行pg_restore触发FileNotFoundError问题

问题解决:subprocess调用pg_restore触发FileNotFoundError

错误原因

你的代码中,subprocess.run的命令参数列表存在格式错误:将命令选项(如-h、-p)与对应的值合并成了单个字符串(比如'-h localhost')。当使用列表形式传递命令参数时,每个选项和它的值必须作为独立的列表元素,否则pg_restore无法正确解析参数,进而引发异常。

修复后的代码

def _dbpath(self) -> Path:
    filepath = Path(__file__).parent.parent.joinpath('postgres')
    return filepath
try:
    command = [
        'pg_restore',
        '-h', 'localhost',
        '-U', _DBUSER,
        '-d', _DBNAME,
        '-p', str(_DBPORT),
        str(self._dbpath())
    ]
    env = dict(os.environ, PGPASSWORD=_DBPWD)
    subprocess.run(command, check=True, env=env)
except BaseException as e:
    print(e)

说明

  • 将'-h localhost'拆分为'-h'和'localhost','-p {_DBPORT}'拆分为'-p'和str(_DBPORT),确保每个命令参数独立。
  • 这种格式符合subprocess列表模式的参数传递规范,pg_restore能正确识别所有选项和对应的值,解决参数解析错误导致的异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 15:32:04