python - 从外部模块执行全局变量

标签 python string exec global python-module

我有一个 extern 模块,我想将“exec”表达式设置为全局(因为我需要将字符串作为变量名称传递)

所以,我有一个类似的功能

def fct_in_extern_module():
    exec 'A = 42' in globals()
    return None

在我的主脚本中我有

import extern_module
extern_module.fct_in_extern_module()

那么,为什么我有

NameError: name 'A' is not defined

如果我这样做(在主脚本中)

def fct_in_main():
    exec 'B = 42' in globals()

fct_in_main()

>>> B
42

知道如何将字符串“A”设置为外部模块中的变量名吗?

谢谢!

最佳答案

globals() 表示“模块的全局字典”。因此,您选择的 extern_module.py 编码方式将不会影响任何其他模块的全局字典。

一种修复方法:将其定义为:

def fct_in_extern_module(where):
    exec 'A = 42' in where

并将其命名为:

extern_module.fct_in_extern_module(globals())

当然,像往常一样,exec并不是解决问题的最佳方法。更好:

def fct_in_extern_module(where):
    where['A'] = 42

更快、更干净。

关于python - 从外部模块执行全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31887664/

相关文章:

php - 替代 PHP exec() 函数

python - 删除用户的权限(django)

c - 字符串赋值的类型不完整

c - C 函数中的奇怪行为,字符串未保留

c - execvp/fork——如何捕捉不成功的执行?

error-handling - 在 Golang 中运行 exec.Command 时如何调试 "exit status 1"错误

python - 如何迭代文件夹,但只检索文件的最新版本?

python - 如何将列添加到 sqlite3 python?

python - 使用 Selenium 和 Python,如何检查按钮是否仍然可点击?

c# - C++ AVR 附加到 const char *