gpt4 book ai didi

python - Postgres - 如何在 Windows 上使用 psql 从 Python 执行多行查询?

转载 作者:行者123 更新时间:2023-11-29 13:14:50 25 4
gpt4 key购买 nike

我希望能够使用 psql 运行多行查询,并试图编写一个库函数来执行此操作,但我收到“权限被拒绝”错误 -

import os
import tempfile

sql = 'select 1;'
with tempfile.NamedTemporaryFile('w') as f:
f.write(sql)
cmd = f'psql --file "{f.name}"'
os.system(cmd) # error: Permission denied

最佳答案

这看起来不太好看,但它有效:

f = tempfile.NamedTemporaryFile('w', delete=False)
f.write(sql)
f.close()
cmd = f'psql --file "{f.name}"'
os.system(cmd)
os.remove(f.name)

错误似乎是由于 Windows 无法再次打开文件 -

Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later).

https://docs.python.org/3.6/library/tempfile.html#tempfile.NamedTemporaryFile

关于python - Postgres - 如何在 Windows 上使用 psql 从 Python 执行多行查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50447755/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com