SandyBr
SandyBr

Reputation: 11969

mysql via subprocess doesn't work

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()

That's my code to connect to mysql and execute query.sql. Looks good to me, but it doesn't work and the bad thing is that I don't get any error message at all. retcode is 1 and from stdout, stderr I only get the mysql standard text "Usage mysql [OPTIONS] [Database] ..." so I thought my syntax is wrong. But it's not. I tested the line of code in terminal and it works.

Does python have a problem to execute this via subprocess? I just want an easy way to execute this small mysql code. Thanks.

Upvotes: 3

Views: 5092

Answers (2)

mmmmmm
mmmmmm

Reputation: 32661

This is not a direct answer but if you are trying to call MySQL from python it will usually be easier and more controllable to call via a DBAPI library see python wiki or going further as ORM like SQLAlchemy

An Example for calling mySQL is here

Upvotes: 1

AndiDog
AndiDog

Reputation: 70128

cmdline = ['mysql -u"username" -p"password" < query.sql']

This is not the way to use Popen. The program must be the first element of the list, and each argument that should be passed must be an element of the list, too. So it should rather be cmdline = ["mysql", "-u", username, "-p", password]. Furthermore, this is not the shell, so you can't simply use "< query.sql". Instead, use the stdin = PIPE parameter and then pass the SQL query like p.communicate(sqlQuery).

retcode = p.wait()

You already waited for the process to end using .communicate(), so you should access the return value with the p.returncode attribute.

Upvotes: 7

Related Questions