I am writing a Python function that needs to export a MySQL database to a .sql file using bash. I am using the mysqldump command.
mysqldump -u bandana -p movies > /Users/Mac/Downloads/testOutput.sql
This command works well enough for my purposes. My question is how to convert this into a Python script that can be run from a function.
I tried using os.system, but I need to enter the password in the terminal during operation.
def cloneDB(): os.system("mysqldump -u bandana -p movies > /Users/Tis_Me/Downloads/testOutput.sql") 输入密码:
I also tried using the subprocesses module, but I don't know anything about it. I just get some errors that I don't know how to fix.
def cloneDB(): subprocess.run(["mysqldump", "-u bandana", "-p movies", "> /Users/Tis_Me/Downloads/testOutput.sql"])
I was wondering if there are any extra parameters or something else I could add to automate the password entry so the function doesn't need to ask for the password.
The desired result is that the cloneDB() function runs without asking for a password.
You can put the password directly on the command line, immediately after
-p
You also cannot put output redirection in the parameter list. That's shell syntax, not command parameters. You can use the
stdout
option ofsubprocess.run()
to redirect its output.