[英]How can i get the list of databases in Postgresql in python
我想在python list中获取Postgresql
服务器中所有数据库的列表。 基本上,那么我想创建那些insode另一个数据库,但是我无法获取它。
这就是我尝试过的
config_read = {
'host':'psql-002',
'database':'tesdb',
'user':'pguser',
'port':'5432',
'password':'mypass'
}
class ExportPSQL():
def __init__(self):
try:
conn = psycopg2.connect(**config_read)
self.conn = conn
except:
print "Eror Connecting database"
def run(self):
# Get a list of databases with :
db_command=" psql -h localhost -U pguser tesdb -c '\l'"
db_list = os.popen(db_command)
使用pg_dumpall
和psql
作为超级用户来完成所有操作
pg_dumpall -h localhost -U postgres -f pg_dumpall.sql
如果只想复制模式,则使用--schema-only
参数。
还原到另一个群集
psql -f pg_dumpall.sql postgres
解决方案中缺少的是读取和解析从psql
获得的信息:
def get_database_info(host, user):
records, _ = subprocess.Popen(['psql','-lA','-F\x02','-R\x01','-h',host,'-U',user ],stdout=subprocess.PIPE).communicate()
records = records.split('\x01')
header = records[1].split('\x02')
return [dict(zip(header,line.split('\x02'))) for line in records[2:-1]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.