David Rojo David Rojo - 10 months ago 85
MySQL Question

Execute mysqldump with python and set the password via stdin

I want to execute a mysqldump in python and provide the password when it is requested from the mysqldump.

Adding the password in the command line is not an option, it must be provided via stdin.

This is what I've done so far:
command = [
'-h', mysqlhost,
'-P', mysqlport,
'-u', mysqluser,

mysqlfile = mysqlpath + "/" + mysqldb + ".sql"
with open(mysqlfile, "w+") as file:
p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=file)

But when I execute the code the terminal hangs requesting the password.

Thank you.

Answer Source

You can use pexpect for that. This is modified code as I had to test it, but you get the idea:

import pexpect

command2 = 'mysqldump -h localhost -u root -p xyzzy'

mysqlfile = "/tmp/foo.sql"
with open(mysqlfile, "w+") as file:
    p = pexpect.spawn(command2)
    p.expect("Enter password: ")
    q = p.read()

here "foobar" is my database password.