从数据库执行Python代码时的语法错误
我正在从数据库加载一些Python代码(这样我可以在运行时动态地改变值,而不需要重新部署代码)。
在我的代码中,我是这样执行数据库里的代码的:
if lMapping:
print lMapping
exec lMapping
lValue = mapping(lValue, lCsvRow)
这是lMapping的值:
def mapping(pValue, pCsvRow):
lInterimStatus = pCsvRow[5]
lOutComeStatus = pCsvRow[6]
if len(lInterimStatus) == 0:
lStatus = lOutComeStatus
else:
lStatus = lInterimStatus
lStatus = lStatus.lower()
PRIMARY_STATUS_MAPPINGS = {
'completed with lender' : '4828',
'not taken up' : '4827',
'declined across all lenders' : '4726',
'declined broker duplicate' : '4726',
'pending' : '4725',
'pending (in progress with broker)' : '4725',
'pending (in progress with lender)' : '4725',
'lender accept in principle' : '4827',
'lender decline duplicate' : '4743',
'lender decline post code not supported' : '4743',
'lender decline score fail' : '4743',
'lender decline policy fail' : '4743',
'lender decline no client contact' : '4743',
'lender decline general' : '4743',
'lender decline bad data' : '4743',
}
return PRIMARY_STATUS_MAPPINGS[lStatus]
每次我这样做的时候,exec那一行都会出现语法错误,我搞不清楚为什么:
(<type 'exceptions.SyntaxError'>:无效的语法 (<string>, 第1行)
更新
如果我先把数据库里的代码写到一个文件里,它就能正常工作:
print lMapping
lFile = open('/mapping.py','w')
lFile.write(lMapping)
lFile.close()
lReadFile = open('/mapping.py')
exec lReadFile
lValue = mapping(lValue, lCsvRow)
1 个回答
1
你有没有用BLOB或者其他的二进制类型的列来存储代码?否则数据库可能会改变行结束符,这样执行的时候就会出现SyntaxError
错误:
>>> s='''\
... print 'ok'
... '''
>>> s
"print 'ok'\n"
>>> exec s
ok
>>> exec s.replace('\n', '\r\n')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
print 'ok'
^
SyntaxError: invalid syntax
更新: 在Windows上以文本模式写入文件会把行结束符改成平台本地的格式。还有一种方法可以让它们保持一致:
lMapping = os.linesep.join(lMapping.splitlines())