从数据库执行语法错误python代码

编程入门 行业动态 更新时间:2024-10-27 10:30:48
本文介绍了从数据库执行语法错误python代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在从数据库中加载一些python代码(它正在动态映射我可以在运行时更改的值,而无需重新部署代码).

I'm loading some python code from a database (it's doing dynamic mapping of values that I can change at runtime without a code redeploy).

在我的代码中,我正在这样做以执行数据库代码:

In my code, I'm doing this to execute the database code:

if lMapping: print lMapping exec lMapping lValue = mapping(lValue, lCsvRow)

这是lMapping的值:

and here's the value of 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行上收到语法错误,我无法弄清原因:

Whenever I do this I'm getting a syntax error on the exec line, I can't work out why:

(<type 'exceptions.SyntaxError'>:invalid syntax (<string>, line 1)

如果我先将代码从数据库写到文件中,它将起作用:

It works if I write the code from the database to a file first:

print lMapping lFile = open('/mapping.py','w') lFile.write(lMapping) lFile.close() lReadFile = open('/mapping.py') exec lReadFile lValue = mapping(lValue, lCsvRow)

推荐答案

您是否使用BLOB或其他 binary 类型列来存储代码?否则数据库可能会更改行尾并且exec将以SyntaxError断开:

Do you BLOB or other binary type column to store code? Otherwise database might change line endings and exec will break with 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上以文本模式写入文件会将行尾更改为平台本地行尾.标准化它们的另一种方法是:

Update: Writing to file on Windows in text mode will change line endings to platform native ones. Another way to normalize them is:

lMapping = os.linesep.join(lMapping.splitlines())

更多推荐

从数据库执行语法错误python代码

本文发布于:2023-10-28 00:40:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1534991.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语法错误   代码   数据库   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!