简体   繁体   English

exec: SyntaxError: 'return' 外部函数

[英]exec: SyntaxError: 'return' outside function

I'm storing code snippets inside the Postgres DB.我将代码片段存储在 Postgres 数据库中。 When I need the code, I find it inside the DB and use exec() function.当我需要代码时,我会在数据库中找到它并使用exec()函数。 The code snippet is a body of extract function.代码片段是extract函数的主体。

Unfortunately it returns SyntaxError: 'return' outside function不幸的是它返回SyntaxError: 'return' outside function

Method方法

def extract(self,response):
    exec(self.custom_code)

Code snippet (repr(code_snippet))代码片段(repr(code_snippet))

u"return response.xpath('/text()')"

I suppose that it should behave like this:我想它的行为应该是这样的:

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.这只是一行代码片段,我需要执行多行代码片段。

EDIT:编辑:

I'm using Django with PostgreSQL and I realised that it strips spaces at the beginning of the line - indentation.我将 Django 与 PostgreSQL 一起使用,我意识到它在行首删除了空格 - 缩进。 I don't know if it has to do something with the problem.我不知道它是否与问题有关。

EDIT2:编辑2:

Tried eval instead of exec.尝试 eval 而不是 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 the exec docs :根据exec文档

Be aware that the return and yield statements may not be used outside of function definitions even within the context of code passed to the exec statement.请注意,即使在传递给exec语句的代码上下文中,也不能在函数定义之外使用returnyield语句。

So exec is explicitly off-limits.所以exec是明确禁止的。 And that wording is global, not specific to exec ;并且该措辞是全球性的,并非特定于exec on checking, while eval using code compile -ed in 'single' mode has the same error;在检查时,在'single'模式下使用代码compile -ed 的eval具有相同的错误; you can't dynamically insert return statements like this.你不能像这样动态插入return语句。

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:因此,不是存储u"return response.xpath('/text()')" ,而是存储u"response.xpath('/text()')" ,并且执行动态调用的代码将更改为:

def extract(self,response):
    return eval(self.custom_code)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM