Python从.gz文件导入数据库

时间:2019-03-18 14:50:56

标签: python mysql sql docker

我使用的工具可以在.gz压缩文件中获取MySQL和Postgresql的数据库转储。这是我之前(使用python)无缝导出的文件。但是,当我需要测试导入时,这不起作用。

该工具在docker容器内工作。提供了我的python代码,

def cmd_schema_import(self, args=None):


    self.require_configured(with_containers=True)
    compressed_import_file = os.path.join(self.project_path, "database", config['database_backup'])

    # no file exist for the database import
    if (not os.path.isfile(compressed_import_file)):
        return

    # run mysql dump
    u, p, d = config['default_db_user'], config['default_db_pass'], config['default_db_name']
    command = f'mysqldump -u {u} -p"{p}" {d}'

    if self.project_conf["db_driver"] == "pgsql":
        command = f'exec psql --quiet -U {u} -d "{d}"'

    additional_options = "| gunzip < %s --keep" % compressed_import_file
    self.docker.exec(self.db_container, command, additional_options)

该函数调用提供的docker方法

def exec(self, container_target, command, additional_options=""):
    """ execte docker exec commmand and return the stdout or None when error"""
    cmd = """docker exec -i "%s" sh -c '%s' %s""" % (
        container_target, command, additional_options)
    if self.verbose:
        print(cmd)
    try:
        cp = subprocess.run(cmd,
                            shell=True,
                            check=True,
                            stdout=subprocess.PIPE)
        return cp.stdout.decode("utf-8").strip()
    except Exception as e:
        print(f"Docker exec failed command {e}")
        return None

我尝试调试代码,但这是挂起的地方,

cp = subprocess.run(cmd,
                            shell=True,
                            check=True,
                            stdout=subprocess.PIPE)

我感谢任何建议。

0 个答案:

没有答案