python - 如何使用 Python 执行 Shell 命令以恢复数据库 postgres?
问题描述
我在 Linux 上恢复我的数据库模板,如下所示: Linux 终端:
su postgres
psql
create database test3;
\q
pg_restore -v -d test3 /opt/empty-db_template.backup
exit
systemctl restart postgresql-11.service
并做了!。但是,当我在 python 中执行 Shell 命令时,如卡在psql
步骤中所示,我该如何解决?
import os
os.system('ls')
os.system('su postgres')
os.system('psql')
os.system('create database test3;')
os.system('\q')
os.system('pg_restore -v -d test3 /opt/empty-db_template.backup')
os.system('exit')
os.system('systemctl restart postgresql-11.service')
解决方案
你在这里做什么是行不通的。 su
创建一个新的外壳。它将等待来自控制台的更多输入。psql
在退出su
shell之前,您将没有机会输入命令。您要么需要以postgres
用户身份运行此命令,要么重复使用该su
命令,或者只需创建一个 shell 脚本并运行该 shell 脚本。
os.system( 'su postgres createdb test3' )
os.system( 'su postgres pg_restore ... ' )
os.systen( 'systemctl restart postgresql-11.service' )
推荐阅读
- java - 如何确定Java中数据库页面的内容何时被更改?
- mysql - MySQL IFNULL 不返回结果
- json - HTTP 406 不可接受的响应标头提琴手
- matlab - 在 MATLAB 中使用 predict() 时出现“未指定有效系统或数据集”
- python - 如何获取python顶层程序的顶层变量列表?
- python - 您如何获得通过数据框中的值搜索的特定值?
- ios - 线程 1:EXC_BAD_ACCESS(代码=1,地址=0x8000000000000010)
- vmware - 无法将 vmware-ovftool 放入卸载列表
- postgresql - 在触发器内调用的 postgres 函数中的 select 语句
- node.js - 使用 Angular CLI 反向代理 API Gateway/lambda 中的服务