# 定义一个字典来存储局部变量local_vars = {}# 动态生成要执行的代码code = """def example_function(x):if x > 0:return x * 2else:return -xresult = 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 * 2else:return -xresult = 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 * 2else:return -xresult = 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 sysdef 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] = modulespec.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