2015-04-17 53 views
1

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

的命令是:

 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 
+1

你为什么要这样做,而不是使用mysql库直接连接? –

回答

0

我同意来自@Daniel Roseman的评论,但是您是否尝试过用单引号代替S上的双引号QL命令?就像这样:

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

或者,也许双反斜线,转义反斜线,而不是报价,蟒串...

0

有,为什么你使用什么原因呢?

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

无法测试上一个co因为我没有这里的MySQL ...

希望这会帮助你找到解决方案。


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

相关问题