使用子进程导入 SQL 转储 [英] Import SQL dump with subprocess

查看:70
本文介绍了使用子进程导入 SQL 转储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过 Python 和子进程将 .sql 转储从磁盘导入 MySQL.IE.相当于

I'm trying to import a .sql dump from disk into MySQL via Python and subprocess. I.e. the equivalent to

mysql -u user -ppassword db < dump.sql

我的 Python 代码看起来像这样(但我尝试了很多替代方法 :)):

My Python code looks like this (but I have tried a ton of alternatives :)):

proc = subprocess.Popen(
    ("mysql -u %s -p%s database"  % (MYSQL_USER, MYSQL_PASSWORD)).split(),
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    shell=False)
out, err = proc.communicate('source /tmp/dump.sql')

应用程序成功完成,但没有导入到 MySQL 的行.我也试过管道 dump.sql 像这样:

The application finishes successfully, but there are no rows imported to MySQL. I have also tried pipe the dump.sql like this:

proc = subprocess.Popen(
    ("mysql -u %s -p%s database < /tmp/dump.sql"  % (MYSQL_USER, MYSQL_PASSWORD)).split(),
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    shell=False)
out, err = proc.communicate()

如果重要,当我设置 shell=True 我得到 ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO))

If important, when I set shell=True I get ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO))

有人能指出我正确的方向吗?

Can anyone please point me in the right direction?

推荐答案

您使用的 Popen.communicate() 错误.

You are using Popen.communicate() wrong.

import subprocess

proc = subprocess.Popen(["mysql", "--user=%s" % USER, "--password=%s" % PASS, "database"],
                        stdin=subprocess.PIPE,
                        stdout=subprocess.PIPE)
out, err = proc.communicate(file("/tmp/dump.sql").read())

这篇关于使用子进程导入 SQL 转储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆