mysql 命令作为 python 子进程

mysql command as a python subprocess

我想从 python 执行以下命令。当我从 shell 运行 它时,我得到了所需的输出但是用子进程调用它时我得到了一个错误。

命令是:

        to_date=`date +%Y-%m-%d`; mysql -uroot -p**** lportal -e "select COUNT(*) from User_ where loginDate like \"$to_date%\";" | sed 1d

这是我的 python 代码:

    from subprocess import *

    cmd='''  to_date=`date +%Y-%m-%d`; mysql -uroot -p**** lportal -e "select COUNT(*) from User_ where loginDate like \"$to_date%\";" | sed 1d  '''
    cmd_out=Popen(cmd,stdout=PIPE,stdin=PIPE,shell=True,stderr=PIPE).communicate()
    print cmd_out

这是我得到的错误,我知道它与 \" 相关,但不知道如何解决它。

    ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-04-17%' at line 1

我同意@Daniel Roseman 的评论,但是您是否尝试过在 SQL 命令中使用单引号而不是双引号?像这样:

select COUNT(*) from User_ where loginDate like '$to_date%';

或者在 python 字符串上加倍反斜杠,以转义反斜杠而不是引号...

你有使用的理由吗?

`date +%Y-%m-%d`

而不是:

import time
date = time.strftime("%Y-%m-d", time.localtime())

当我做这样的事情时,我总是使用这种方法:

import subprocess
cmd = 'xterm -display {} -e {}'.format(display, command)
status = subprocess.call(cmd.split())

该命令读起来会更清晰:

cmd = 'mysql -u {} -p {} lportal -e "select COUNT(*) from User_ where loginDate like "{}" | sed 1d'.format(username, password, date)

无法测试最后一个命令,因为我这里没有 mysql...

希望这能帮助您找到解决方案。


但老实说,我绝不会这样查询数据库。 Daniel Roseman 是完全正确的,你应该使用 mysql 库来实现你想要的,而不需要太多的努力。