0

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.

1
  • "-u bandana" should be "-u", "bandana" Commented Jun 30, 2023 at 23:04

1 Answer 1

0

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)
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks so much! Completely solves my problem.
I am getting this error on last line in this code : 'expected str, bytes or os.PathLike object, not set'. Plus where to write host?
Host would be "-h", "hostname" in the argument list. Just like when you type the command by hand.
Nothing in my code creates a set, so I don't see how you could be getting that error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.