pythonmysqlsubprocesspython-os

Running a bash command in Python, when said bash command requires a password?


I'm writing a Python function that requires exporting a MySQL database into a .sql file with bash. For it, I'm using mysqldump.

mysqldump -u bandana -p movies > /Users/Mac/Downloads/testOutput.sql

The command works fine enough for my purposes. My problem is translating this to be run in a python script from a function.

I tried using os.system, but then I have to enter the password in the terminal while it runs.

def cloneDB():
    os.system("mysqldump -u bandana -p movies > /Users/Tis_Me/Downloads/testOutput.sql")

Enter password: 

I also tried using the subprocesses module, but I have no clue what I'm doing there. I just end up getting errors I don't understand how to solve.

def cloneDB():
    subprocess.run(["mysqldump", "-u bandana", "-p movies", "> /Users/Tis_Me/Downloads/testOutput.sql"])

What I'm asking is whether there's any extra arguments or something I could add to automate inputing the password, so the function doesn't have to ask for the password at all.

THE DESIRED RESULT is for the cloneDB() function to run without having to ask for a password.


Solution

  • You can put the password in the command line itself, immediately after -p

    You also can't put output redirection in the argument list. That's shell syntax, not command arguments. You can use the stdout option to subprocess.run() to redirect its output.

    def cloneDB():
        password = "something"
        with open("/Users/Tis_Me/Downloads/testOutput.sql", "w") as sqlfile:
            subprocess.run(["mysqldump", "-u", "bandana", f"-p{password}", "movies"], stdout=sqlfile)