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

 

posted @ 2022-03-21 11:45  淋哥  阅读(2723)  评论(0编辑  收藏  举报