search

Home  >  Q&A  >  body text

How to solve the problem of running bash commands that require password in Python

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粉476046165P粉476046165244 days ago598

reply all(1)I'll reply

  • P粉647504283

    P粉6475042832024-03-23 10:40:23

    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)

    reply
    0
  • Cancelreply