How to copy a database with mysqldump and mysql in Python?

后端 未结 3 594
名媛妹妹
名媛妹妹 2021-01-03 05:07

I am writing a simple Python script to copy a MySQL database. I am attempting to copy the database based on the following SO questions and their answers: \"Copy/duplicate da

3条回答
  •  萌比男神i
    2021-01-03 05:42

    Here's how you could run mysqldump .. | mysql pipeline without the shell:

    #!/usr/bin/env python
    from subprocess import Popen, PIPE
    
    mysql = Popen("mysql -h localhost -P 3306 -u root -p mydb2".split(),
                  stdin=PIPE, stdout=PIPE)
    mysqldump = Popen("mysqldump -h localhost -P 3306 -u root -p mydb".split(),
                      stdout=mysql.stdin)
    mysql_stdout = mysql.communicate()[0]
    mysqldump.wait()
    

    See How do I use subprocess.Popen to connect multiple processes by pipes?

    If you don't need to pass command-line parameters that require complex (possibly non-portable) escaping, capture the exit statuses, stdout then it is simpler to use the shell here.

提交回复
热议问题