在Python中,如何在共享上下文中使用多个exec调用?

2024-04-28 02:58:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个Python程序来执行Verilog脚本中嵌入的Python代码。我曾想过使用evalexec函数,但遇到了一个问题:我希望所有的execeval都在共享的上下文中运行,而不改变主程序的环境。你知道吗

我将execeval放入一个函数中,以便在解析例程中调用:

# some parsing code
for embedded_code_string in list_of_embedded_code_strings:
    execute_embedded_code(embedded_code_string)
# more parsing code
def execute_embedded_code(embedded_code_string):
    exec(embedded_code_string)
    # other routines involving io.StringIO for the redirection of stdout which isn't the problem.

如果要运行的第一个嵌入式代码字符串是row_len = 1,第二个是column_len = row_len * 2,那么在运行第二个代码段时,row_len将是未定义的。应该是这样的:毕竟exec是在函数execute_embedded_code的上下文中运行的,函数完成后,变量将从locals()globals()中消失。你知道吗

似乎可以为exec设置本地和全局名称空间。但是,运行exec后的更改不会保留在适当的位置。(更正:global\u dict和local\u dict参数必须是字典,否则将被忽略。如果它是一个字典,它将被就地更新。)在exec之后运行globals()locals()将捕获更改,但它也将捕获解析程序中的对象,我不希望嵌入的代码无意中弄乱解析程序。你知道吗

所以我的问题是,我如何在它们的共享上下文中运行许多exec调用,并且保持足够的隔离,以避免它们产生意外的后果。无需考虑安全性,因为运行的所有嵌入代码都是可信的。你知道吗

我想获得每个嵌入式代码字符串的单独输出,所以我不认为将它们连接在一起并一次运行它会奏效。你知道吗


Tags: ofthe函数代码程序forexecutestring
1条回答
网友
1楼 · 发布于 2024-04-28 02:58:46

您应该能够定义自己的共享globals,并将其传递给exec,然后由嵌入的代码修改:

def execute_embedded_code(embedded_code_string, shared_globals):
    exec(embedded_code_string, shared_globals)

shared_globals = dict()
shared_globals['result'] = 0
sample_string = 'result += 1'
execute_embedded_code(sample_string, shared_globals)
print(shared_globals['result'])

输出

1

注意

为了处理下面的注释,documentation for exec表示

If only globals is provided, it must be a dictionary, which will be used for both the global and the local variables.

相关问题 更多 >