How to solve the problem of running bash commands that require password in Python
P粉476046165
P粉476046165 2024-03-22 13:20:24
0
1
600

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.

P粉476046165
P粉476046165

reply all(1)
P粉647504283

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 of 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)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template