python - 为什么我从 python 脚本中得到“psql:服务器意外关闭连接”?
问题描述
我有一个 python 脚本,它首先使用 docker-py 库创建一个 postgres docker 容器:
client = docker.from_env()
CONTAINER = 'test_cont'
container = client.containers.run("postgres", ports={'5432/tcp': 27432},
environment=["POSTGRES_PASSWORD=password",
"POSTGRES_DB=my_db"],
name=CONTAINER,
detach=True)
docker 容器正确启动。我想从 python 脚本运行一些命令,所以我尝试了:
subprocess.call('psql -h localhost -p 27432 -U postgres -c "CREATE USER xxx WITH PASSWORD \'password\';"', shell=True, env={'PGPASSWORD': 'password'})
但是,此命令总是返回以下错误:
psql: server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
如果我从命令行而不是从 python 代码运行 psql 命令,它可以正常工作。
解决方案
解决了这个问题,如果我们在守护进程模式下运行 postgres docker 容器,它不会等待 postgres 服务器完成启动序列,因此 psql 命令在 postgres 服务器完成启动之前运行。为了解决这个问题,我在 python 脚本中的 docker run 命令之后添加了一个睡眠时间,以允许数据库启动。
推荐阅读
- python - 使用 pip 安装模块后无法在 python 中导入模块
- reactjs - 如何在 React Material-UI 应用程序中更新 react-chartjs-2 条形图的选项而不重新渲染?
- latex - 如果值具有乳胶标记,则乳胶宏中的键值查找系统将失败
- reactjs - (React,Regex)如何为每个过滤的重复输入值创建新的输入表单?
- mysql - 如何在 SQL 数据库中表示非 SQL 自定义模式结构
- spring - Google Kubernetes Engine Spring Boot 应用程序无法连接到同一网络内的数据库
- excel - EXCEL VBA - 将每个选定的单元格范围传递给宏
- php - PHP遍历编码为数组的嵌套数组
- sql - 联接表并仅添加具有特定值的列
- git - Composer 使用 https 而不是 ssh(用于 GitLab)