我收到此错误:
File "/DateDbLoop.py", line 33
d.Id""" % (str(day), str(2840))"
^
SyntaxError: EOL while scanning single-quoted string
这是脚本。有4个双引号可以打开这个,但我不确定如何正确关闭它?
跟进问题:
这个%(str(day),str(2840))是否需要同时进入sql变量和os.system()调用?
#!/usr/bin/python
import datetime
import sys, os, time, string
a = datetime.date(2009, 1, 1)
b = datetime.date(2009, 2, 1)
one_day = datetime.timedelta(1)
day = a
while day <= b:
print "Running query for \"" + str(day) + "\""
sql=""""SELECT
d.Date,
SUM(d.Revenue),
FROM Table d
WHERE d.Date = '%s'
AND d.Id = %s
GROUP BY d.Date
""" % (str(day), str(2840))"
os.system('mysql -h -sN -u -p -e %s > FileName-%s.txt db' % (sql, str(day)))
day += one_day
答案 0 :(得分:5)
你的sql = line有4个双引号,而不是3。同时删除%-substitution值后的单引号。
#!/usr/bin/python
import datetime
import sys, os, time, string
a = datetime.date(2009, 1, 1)
b = datetime.date(2009, 2, 1)
one_day = datetime.timedelta(1)
day = a
while day <= b:
print "Running query for \"" + str(day) + "\""
sql="""SELECT
d.Date,
SUM(d.Revenue)
FROM Table d
WHERE d.Date = '%s'
AND d.Id = %s
GROUP BY d.Date
""" % (str(day), str(2840))
os.system('mysql -h -sN -u -p -e "%s" > FileName-%s.txt db' % (sql, str(day)))
day += one_day
多行字符串值是在Python中使用双引号的成对三元组完成的,不要嵌套在常规双引号内。
答案 1 :(得分:1)
用三个引号打开和关闭字符串
sql = """
SELECT d.Date, SUM(d.Revenue),
FROM Table d WHERE d.Date = '%s' AND d.Id = %s
GROUP BY d.Date
""" % (str(day), str(2840))
您还可以使用\字符在字符串中间打破一行。
#!/usr/bin/python
import datetime
import sys, os, time, string
a = datetime.date(2009, 1, 1)
b = datetime.date(2009, 2, 1)
one_day = datetime.timedelta(1)
day = a
while day <= b:
print "Running query for \"" + str(day) + "\""
sql="SELECT d.Date, SUM(d.Revenue), FROM Table d WHERE d.Date = '%s' \
AND d.Id = %s GROUP BY d.Date " % (str(day), str(2840))
os.system('mysql -h -sN -u -p -e %s > FileName-%s.txt db' % (sql, str(day)))
答案 2 :(得分:0)
您可以使用三重引号。
s = """
Python is awesome.
Python is cool.
I use Python.
And so should you.
"""
print s
Python is awesome.
Python is cool.
I use Python.
And so should you.