Mysql through subprocess not working

import os
import subprocess
cmdline = ['mysql -u"username" -p"password" < query.sql']
p = subprocess.Popen(cmdline,stdout=subprocess.PIPE)
stdout,stderr = p.communicate()
retcode = p.wait()

So that my code connects to mysql and runs query.sql. It looks good, but it does not work, and the bad thing is that I do not receive an error at all. retcode is 1 and from stdout, stderr I get only the standard mysql text "Using mysql [OPTIONS] [Database] ...", so I thought my syntax was wrong. But this is not so. I tested a line of code in a terminal and it works.

Does python have a problem to execute this through a subprocess? I just want an easy way to execute this little mysql code. Thank.

+3
source share
2 answers
cmdline = ['mysql -u"username" -p"password" < query.sql']

Popen. , , , . cmdline = ["mysql", "-u", username, "-p", password]. , , "< query.sql". stdin = PIPE, SQL, p.communicate(sqlQuery).

retcode = p.wait()

.communicate(), p.returncode.

+6

, MySQL python, DBAPI . python wiki , ORM, SQLAlchemy

mySQL

+2

Source: https://habr.com/ru/post/1791660/


All Articles