簡體   English   中英

exec: SyntaxError: 'return' 外部函數

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

我將代碼片段存儲在 Postgres 數據庫中。 當我需要代碼時,我會在數據庫中找到它並使用exec()函數。 代碼片段是extract函數的主體。

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

方法

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

代碼片段(repr(code_snippet))

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

我想它的行為應該是這樣的:

def extract(self,response):
    return response.xpath('/text()')

我應該怎么做? 這只是一行代碼片段,我需要執行多行代碼片段。

編輯:

我將 Django 與 PostgreSQL 一起使用,我意識到它在行首刪除了空格 - 縮進。 我不知道它是否與問題有關。

編輯2:

嘗試 eval 而不是 exec。 現在它提出:

  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

根據exec文檔

請注意,即使在傳遞給exec語句的代碼上下文中,也不能在函數定義之外使用returnyield語句。

所以exec是明確禁止的。 並且該措辭是全球性的,並非特定於exec 在檢查時,在'single'模式下使用代碼compile -ed 的eval具有相同的錯誤; 你不能像這樣動態插入return語句。

如果您絕對必須允許執行任意代碼,我強烈建議將其限制為表達式,而不是語句,並隱式返回所述表達式的結果。 因此,不是存儲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