【发布时间】:2017-09-07 13:03:04
【问题描述】:
使用 Popen 运行 PostgreSQL 查询。这有效:
maxId = 10
psql = "psql -d db -U user -t -c 'select id, experiment_id from results where id > " + maxId + "'"
ssh = subprocess.Popen(['ssh', 'me@server', psql],
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
result = ssh.stdout.readlines()
当我添加一个like子句时,它失败了:
psql = "psql -d db -U user -t -c 'select id, experiment_id from results where status like '%Completed%' and id > " + maxId + "'"
['ERROR: syntax error at or near "%"\n', 'LINE 1: ...t_id" from results where status like %Completed...\n', ' ^\n']
我尝试了几种引用替代方案,但似乎无法正确。
任何帮助将不胜感激。
TD
更新: 终于能够在对 psql 的调用以及在单引号中传递 like 子句的原始问题中保留双引号列名。解决方法如下:
在这里找到提示:Keeping double quotes when passing string to popen in C
psqlcmd = 'psql -U choa -d iondb -t -c '
sql = "\"select id, experiment_id, \\\"resultsName\\\" from rundb_results where status like '%Completed%' and id > 5;\""
print(psqlcmd)
print(sql)
ssh = subprocess.Popen(['ssh', 'me@server', psqlcmd, sql],
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
result = ssh.stdout.readlines()
【问题讨论】:
标签: python string postgresql popen