首页 > 解决方案 > 如何使用 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步骤中所示,我该如何解决?

陷入 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')

标签: pythonlinuxshell

解决方案


你在这里做什么是行不通的。 su创建一个新的外壳。它将等待来自控制台的更多输入。psql在退出sushell之前,您将没有机会输入命令。您要么需要以postgres用户身份运行此命令,要么重复使用该su命令,或者只需创建一个 shell 脚本并运行该 shell 脚本。

os.system( 'su postgres createdb test3' )
os.system( 'su postgres pg_restore ... ' )
os.systen( 'systemctl restart postgresql-11.service' )

推荐阅读