python3 執行代碼塊,並返回數據 exec 返回值

Python3 exec 函數

描述

exec 執行儲存在字符串或文件中的 Python 語句,相比於 eval,exec可以執行更復雜的 Python 代碼。

語法

以下是 exec 的語法:

exec(object[, globals[, locals]])

參數

  • object:必選參數,表示需要被指定的 Python 代碼。它必須是字符串或 code 對象。如果 object 是一個字符串,該字符串會先被解析爲一組 Python 語句,然後再執行(除非發生語法錯誤)。如果 object 是一個 code 對象,那麼它只是被簡單的執行。
  • globals:可選參數,表示全局命名空間(存放全局變量),如果被提供,則必須是一個字典對象。
  • locals:可選參數,表示當前局部命名空間(存放局部變量),如果被提供,可以是任何映射對象。如果該參數被忽略,那麼它將會取與 globals 相同的值。

返回值

exec 返回值永遠爲 None。

 

exec 返回值永遠爲 None,那麼如何返回結果呢?

直接上代碼

  

# -*- coding: utf-8 -*-

func_str = """

all_data = [
        {'seed-url': 'https://rf.eefocus.com/', 'list-url': 'https://rf.eefocus.com/article/list-all/sort-new?p={}', 'pages': int(3)},
]

def generator():
    url_list = []
    for data in all_data:
        url = data['list-url']
        pages = data['pages']
        for page in range(1, int(pages)):
            url_list.append(url.format(page))
    return url_list

ab = generator()
print("ab",ab)
aa['ab'] = ab
print("aa",aa)

"""
global aa
aa = {}
rees = exec(func_str)
print("aa----",aa)

  打印結果是:

  

C:\Python37\python3.exe D:/spider/spider_3_test.py
ab ['https://rf.eefocus.com/article/list-all/sort-new?p=1', 'https://rf.eefocus.com/article/list-all/sort-new?p=2']
aa {'ab': ['https://rf.eefocus.com/article/list-all/sort-new?p=1', 'https://rf.eefocus.com/article/list-all/sort-new?p=2']}
aa---- {'ab': ['https://rf.eefocus.com/article/list-all/sort-new?p=1', 'https://rf.eefocus.com/article/list-all/sort-new?p=2']}

Process finished with exit code 0

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章