2

I'd like to execute some Mysql commands from Linux, using Python and its subprocess module.

Without Python, from a shell, my command line is:

mysql --database=mydb --host=localhost --port=3306 --password=  --execute="select * from mytable" --batch

With Python, I have:

cmd = ['mysql']
cmd.extend(['--database=', self._database])
cmd.extend(['--password=', self._password])
cmd.extend(['--execute=', query])

(...)

p = subprocess.Popen(cmd, shell = False, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
out, err = p.communicate()
errcode = p.returncode

Unfortunately, it doesn't work (mysql just print usage) and I think, subprocess generate this kind of output (' '.join(cmd)):

mysql --database= mydb --host= localhost --port= 3306 --password=  --execute= "select * from mytable" --batch

ie. spaces are added between each parameters, separating = and value.

When I remove = in every parameters (cmd.extend(['--password', self._password])), it works fine, except when a parameter is void (so, I test if each parameter is void, then remove it if needed).

Finally, I found a workaround, by testing void parameters, but for future reference, is there any subprocess tip or usage I don't know to handle this kind of parameter= ? There must be some application when you have to use =, and I try to avoid Shell=True.

2 Answers 2

6

Change that to

cmd = [
    'mysql',
    '--database=%s' % self._database,
    '--password=%s' % self._password,
    '--execute=%s' % query
]

(...)

p = subprocess.Popen(cmd, shell = False, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
out, err = p.communicate()
errcode = p.returncode

such that the list of arguments contains switches with their respective arguments

Sign up to request clarification or add additional context in comments.

2 Comments

So simple, yet, I didn't even think of that (I guess I need vacation :) ) Thank you
I like, but how about removing the extend and just do ['mysql', '--database=%s' % self._database, ...] while we're at it?
1

You're passing each argument containing an = sign as two separate arguments. Don't do that, because they're not two separate arguments.

cmd.append('--database=' + self._database)
cmd.append('--password='+ self._password)
cmd.append('--execute=' + query)

(David's suggestion to use [] to define the whole list at once rather than repeated append or extend calls is better style.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.