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

 

方法二:直接上代碼了

 

  

func_str = """
def generator():
    all_data = [
            {'seed-url': 'https://rf.eefocus.com/', 'list-url': 'https://rf.eefocus.com/article/list-all/sort-new?p={}', 'pages': int(3)},
    ]
    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
"""
namespace = {}
fun = compile(func_str,'<string>','exec')
exec(fun,namespace)
ret = namespace['generator']()
print("ret",ret)

輸出結果:

    

C:\Python37\python.exe D:/spider_2022/spider_11_jiagu/test.py
ret ['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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM