简体   繁体   English

使用子进程导入SQL转储

[英]Import SQL dump with subprocess

I'm trying to import a .sql dump from disk into MySQL via Python and subprocess. 我正在尝试通过Python和子进程将.sql转储从磁盘导入MySQL。 Ie the equivalent to 即相当于

mysql -u user -ppassword db < dump.sql

My Python code looks like this (but I have tried a ton of alternatives :)): 我的Python代码看起来像这样(但我尝试了很多替代方案:)):

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

The application finishes successfully, but there are no rows imported to MySQL. 应用程序成功完成,但没有导入MySQL的行。 I have also tried pipe the dump.sql like this: 我也试过像这样管道dump.sql

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()

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

Can anyone please point me in the right direction? 有谁能指出我正确的方向?

If you come to this page from Google, please note, that sigi's answer will work, but it will load all dump file into memory and if it's too big to fit, it will fail. 如果你从谷歌来到这个页面,请注意,sigi的答案是可行的,但它会将所有转储文件加载到内存中,如果它太大而不适合,它将失败。

Here's how I do it: 我是这样做的:

with open(dump_filename, 'r') as f: 
       command = ['mysql', '-u%s' % db_settings['USER'], '-p%s' % db_settings['PASSWORD'], db_settings['NAME']]
       proc = subprocess.Popen(command, stdin = f)
       stdout, stderr = proc.communicate()

It do the same, but memory consumption is minimal, because the dump is streamed right to the stdin of mysql. 它也是这样,但内存消耗很小,因为转储直接流到mysql的stdin。

You are using Popen.communicate() wrong. 您正在使用Popen.communicate()错误。

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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM