动态执行 Python 代码的多种方法

# 定义一个字典来存储局部变量local_vars = {}
# 动态生成要执行的代码code = """def example_function(x):    if x > 0:        return x * 2    else:        return -x
result = example_function(10)"""
# 使用 exec() 执行代码,并将结果存储在 local_vars 中exec(code, {}, local_vars)
# 从 local_vars 中提取结果result = local_vars.get('result')
print(result)  # 输出:20

图片

避免缩进问题

图片

1. 使用三引号字符串

图片

# 定义要执行的多行代码字符串code = """def example_function(x):    if x > 0:        return x * 2    else:        return -x
result = example_function(10)"""
# 使用 exec() 执行代码,并将结果存储在 local_vars 中exec(code, {}, local_vars)

2. 动态生成代码字符串时调整缩进

图片

# 动态生成要执行的代码行code_lines = [    "def example_function(x):",    "    if x > 0:",    "        return x * 2",    "    else:",    "        return -x",    "",    "result = example_function(10)"]
# 将代码行合并成一个字符串code = "n".join(code_lines)
# 使用 exec() 执行代码,并将结果存储在 local_vars 中exec(code, {}, local_vars)

3. 使用 textwrap.dedent 调整缩进

图片

import textwrap
# 使用 textwrap.dedent 调整多行字符串的缩进code = textwrap.dedent("""    def example_function(x):        if x > 0:            return x * 2        else:            return -x
    result = example_function(10)""")
# 使用 exec() 执行代码,并将结果存储在 local_vars 中exec(code, {}, local_vars)

执行 Python 文件

图片

1. 使用 exec 读取并执行文件内容

图片

# 定义文件路径file_path = 'path/to/your_file.py'
# 定义一个字典来存储局部变量local_vars = {}
# 读取文件内容with open(file_path, 'r') as file:    code = file.read()
# 使用 exec() 执行文件内容,并将结果存储在 local_vars 中exec(code, {}, local_vars)
# 从 local_vars 中提取结果(假设文件中定义了一个变量 result)result = local_vars.get('result')
print(result)

2. 使用 importlib 动态导入模块

图片

import importlib.utilimport sys
def exec_py_file(file_path):    # 定义模块名    module_name = 'dynamic_module'
    # 动态导入模块    spec = importlib.util.spec_from_file_location(module_name, file_path)    module = importlib.util.module_from_spec(spec)    sys.modules[module_name] = module    spec.loader.exec_module(module)
    return module
# 使用 exec_py_file 执行文件内容module = exec_py_file('path/to/your_file.py')
# 从模块中提取结果(假设文件中定义了一个变量 result)result = getattr(module, 'result', None)
print(result)

3. 使用 runpy 运行模块

图片

import runpy
# 定义文件路径file_path = 'path/to/your_file.py'
# 使用 runpy 运行文件内容,并获取返回的命名空间namespace = runpy.run_path(file_path)
# 从命名空间中提取结果(假设文件中定义了一个变量 result)result = namespace.get('result')
print(result)

4. 使用 subprocess 执行脚本

图片

import subprocess
# 定义文件路径file_path = 'path/to/your_file.py'
# 使用 subprocess 运行文件内容result = subprocess.run(['python', file_path], capture_output=True, text=True)
# 输出结果print(result.stdout)print(result.stderr)

结论

图片

原创文章,作者:guozi,如若转载,请注明出处:https://www.sudun.com/ask/90966.html

(0)
guozi's avatarguozi
上一篇 2024年6月7日 下午1:58
下一篇 2024年6月7日 下午2:01

相关推荐

  • DNS负责将域名转换为IP地址

      引言 随着互联网技术的迅猛发展,域名系统(DNS)作为互联网的核心组成部分,其重要性日益凸显。DNS通过将人类易于记忆的域名转换为机器可识别的IP地址,极大地简化了网…

    行业资讯 2024年7月28日
    0
  • 动态拨号VPS服务器的作用及搭建方法

    对于网络互联网服务器行业来说,动态拨号VPS服务器是一种非常重要的存在。它不仅可以提供稳定的网络连接,还具有灵活性和安全性,受到越来越多企业和个人的青睐。那么,什么是动态拨号VPS…

    行业资讯 2024年4月1日
    0
  • 廊坊seo

    想要在廊坊地区拥有更好的网络曝光率吗?那就绝对不能错过今天我们要介绍的主题——“廊坊SEO”。作为一种搜索引擎优化技术,SEO在当今的网络营销中扮演着至关重要的角色。但是,什么是S…

    行业资讯 2024年4月18日
    0
  • 如何使用一键登录192.168.0.1设置网络互联网服务器?

    您是否曾经遇到过设置网络互联网服务器的烦恼?或许您对于什么是网络互联网服务器还有些模糊,甚至不知道如何使用一键登录192.168.0.1来设置它。别担心,本文将为您揭开这个行业的神…

    行业资讯 2024年4月19日
    0

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注