问题描述
我将代码片段存储在 Postgres 数据库中.当我需要代码时,我会在数据库中找到它并使用 exec()
函数.代码片段是 extract
函数的主体.
I'm storing code snippets inside the Postgres DB. When I need the code, I find it inside the DB and use exec()
function. The code snippet is a body of extract
function.
不幸的是它返回SyntaxError: 'return' external function
方法
def extract(self,response):
exec(self.custom_code)
代码片段 (repr(code_snippet))
Code snippet (repr(code_snippet))
u"return response.xpath('/text()')"
我想它应该像这样:
def extract(self,response):
return response.xpath('/text()')
我该怎么办?这只是一行代码片段,我需要执行多行代码片段.
What I should do?This is just one line snippet and I need to execute multiline snippets.
我将 Django 与 PostgreSQL 一起使用,我意识到它会在行首删除空格 - 缩进.不知道是不是跟问题有关系.
I'm using Django with PostgreSQL and I realised that it strips spaces at the beginning of the line - indentation. I don't know if it has to do something with the problem.
尝试使用 eval 而不是 exec.现在它提出:
Tried eval instead of exec. Now it raises:
File "/home/milano/PycharmProjects/Stilio_project/stilio/engine/models.py", line 107, in extract
eval(self.custom_code)
File "<string>", line 1
return response.xpath('/text()')
^
SyntaxError: invalid syntax
推荐答案
Per exec
文档:
Per the exec
docs:
请注意,即使在传递给 exec
的代码上下文中,也不能在函数定义之外使用 return
和 yield
语句声明.
所以 exec
是明确禁止的.并且该措辞是全球性的,并非特定于 exec
;在检查时,在 'single'
模式下使用代码 compile
-ed 的 eval
有相同的错误;您不能像这样动态插入 return
语句.
So exec
is explicitly off-limits. And that wording is global, not specific to exec
; on checking, while eval
using code compile
-ed in 'single'
mode has the same error; you can't dynamically insert return
statements like this.
如果您绝对必须允许执行任意代码,我强烈建议将其限制为表达式,而不是语句,并隐式返回所述表达式的结果.因此,不是存储 u"return response.xpath('/text()')"
,而是存储 u"response.xpath('/text()')"
code>,并且您执行动态调用的代码将更改为:
If you absolutely must allow executing arbitrary code, I strongly recommend limiting it to expressions, not statements, and implicitly returning the result of said expressions. So instead of storing u"return response.xpath('/text()')"
, you'd store u"response.xpath('/text()')"
, and your code that performs dynamic invocation would change to:
def extract(self,response):
return eval(self.custom_code)
这篇关于exec: SyntaxError: 'return' 外部函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!