python中exec中变量不能保存_Python 3.4,不能使用exec()创建的变量

在Python 3.4和一个函数中,这段代码出现:

ch0 = 'dico[\''+ ans +'\']' # dico is a dictionary and ans is a key of this dictionary

print('test')

print(list(locals()))

exec('keys2 = list(' + ch0 + ')', locals())

print(list(locals()))

print(locals()['keys2'])

print('keys2:', keys2)

这是输出:

test

['dico', 'save', 'keys0', 'LOG_FILENAME', 'ch0', 'flag', 'completer', 'k', 'ans', 'keys1']

['dico', 'save', 'keys0', 'LOG_FILENAME', 'ch0', 'flag', 'completer', 'k', 'ans', 'keys1', '__builtins__', 'keys2']

['General informations', 'Experiments parameters', 'Calculated parameters']

Traceback (most recent call last):

File "/data_1/dataGestion.py", line 189, in consult_db

print('keys2:', keys2)

NameError: name 'keys2' is not defined

不出所料,我们观察到在本地范围内创建了keys2变量,并且该变量很好地包含了预期值(['General informations,'Experiments parameters','Calculated parameters']),似乎表明了locals返回的字典()。但是无法访问此keys2变量(名称'keys2'未定义!!!)。为什么呢

编辑1:我们看到Keys2在本地范围内,因为在上述问题的代码中:

print(list(locals()))

print(locals()['keys2'])

返回:

['dico', 'keys0', 'save', 'k', 'ans', 'keys1', '__builtins__', 'flag', 'LOG_FILENAME', 'keys2', 'ch0', 'completer']

['General informations', 'Experiments parameters', 'Calculated parameters']

但是!为什么我用以下命令更改上面的代码:

ch0 = 'dico[\''+ ans +'\']' # dico is a dictionary and ans is a key of this dictionary

print('test')

exec('keys2 = list(' + ch0 + ')', locals())

keys2 = locals()['keys2']

print('keys2:', keys2)

没有创建keys2变量,正如我们再次看到的NameError异常所示:

Traceback (most recent call last):

File "/data_1/IRM/amigo/src/IRMAGE_python_modules/IRMAGE_dataGestion.py", line 191, in consult_db

print('keys2:', keys2)

NameError: name 'keys2' is not defined

编辑2:通过继续玩exec()和locals()...考虑以下代码:

ch0 = 'dico[\''+ ans +'\']' # dico is a dictionary and ans is a key of this dictionary

print('test')

namespace = locals()

print(list(namespace))

print(list(locals()))

print(list(globals()))

exec('keys2 = list(' + ch0 + ')', namespace)

keys2 = namespace['keys2']

print()

print(list(namespace))

print(list(locals()))

print(list(globals()))

print('keys2:', keys2)

输出为:

test

['ch0', 'ans', 'completer', 'save', 'keys0', 'keys1', 'k', 'flag', 'dico', 'LOG_FILENAME']

['ch0', 'ans', 'completer', 'save', 'keys0', 'keys1', 'k', 'flag', 'dico', 'LOG_FILENAME', 'namespace']

['__spec__', 'nbLigne', 'remove', 'listdir', 'getSampleStyleSheet', 'Paragraph', '__builtins__', 'system', 'upvivification', '__package__', 'exit', '__doc__', 'AutoVivification', 'recupParameter', 'verSofts', 'logging', 'revivification', 'renameComment', 'unvivification', 'creatExpParameter', 'rlcompleter', 'consult_db', 'makedirs', 'datetime', 'isdir', 'recupCover', 'MyCompleter', 'verifFichier', 'dico2txt', 'para2dic', 'readlineComp', '__name__', '__file__', 'anonym', '__cached__', '__loader__']

['ch0', 'ans', 'completer', 'save', 'keys0', 'keys1', 'k', 'flag', 'dico', 'LOG_FILENAME', 'namespace', '__builtins__', 'keys2']

['ch0', 'ans', 'completer', 'save', 'keys0', 'keys1', 'k', 'flag', 'dico', 'LOG_FILENAME', 'namespace', '__builtins__', 'keys2']

['__spec__', 'nbLigne', 'remove', 'listdir', 'getSampleStyleSheet', 'Paragraph', '__builtins__', 'system', 'upvivification', '__package__', 'exit', '__doc__', 'AutoVivification', 'recupParameter', 'verSofts', 'logging', 'revivification', 'renameComment', 'unvivification', 'creatExpParameter', 'rlcompleter', 'consult_db', 'makedirs', 'datetime', 'isdir', 'recupCover', 'MyCompleter', 'verifFichier', 'dico2txt', 'para2dic', 'readlineComp', '__name__', '__file__', 'anonym', '__cached__', '__loader__']

keys2: ['Calculated parameters', 'General informations', 'Experiments parameters']

有了这个结果,我知道使用exec()作为参数传递的字典(名称空间)用于在函数exec()的范围内查找变量,但是该字典(名称空间)包含执行exec之后的所有变量。 exec()。这是可以理解的,但是我还不了解为什么在EDIT 1中,key2 = locals()['keys2']在此EDIT 2中不能工作,而keys2 = namespaces('keys2']在工作吗?

编辑3:通过继续玩exec()和locals()...考虑以下代码:

ch0 = 'dico[\''+ ans +'\']' # dico is a dictionary and ans is a key of this dictionary

print('test')

print(list(locals()))

print(list(globals()))

exec("global keys2; keys2 = list(" + ch0 + "); print('\\n** keys2 inside exec function: {}'.format(keys2))", locals())

print()

print(list(locals()))

print(list(globals()))

print('keys2:', keys2)

输出为:

test

['ch0', 'LOG_FILENAME', 'k', 'flag', 'save', 'ans', 'keys0', 'dico', 'completer', 'keys1']

['recupCover', 'MyCompleter', '__name__', 'para2dic', 'readlineComp', 'upvivification', 'listdir', 'verifFichier', 'recupParameter', 'system', 'remove', '__doc__', 'nbLigne', 'renameComment', '__spec__', '__file__', 'anonym', 'creatExpParameter', '__package__', 'isdir', 'revivification', 'exit', '__loader__', 'makedirs', 'datetime', 'consult_db', 'Paragraph', '__cached__', '__builtins__', 'AutoVivification', 'getSampleStyleSheet', 'unvivification', 'rlcompleter', 'logging', 'verSofts', 'dico2txt']

** keys2 inside exec function: ['Experiments parameters', 'Calculated parameters', 'General informations']

['ch0', 'LOG_FILENAME', 'k', 'flag', 'save', 'ans', 'keys0', 'dico', 'completer', 'keys1', '__builtins__', 'keys2']

['recupCover', 'MyCompleter', '__name__', 'para2dic', 'readlineComp', 'upvivification', 'listdir', 'verifFichier', 'recupParameter', 'system', 'remove', '__doc__', 'nbLigne', 'renameComment', '__spec__', '__file__', 'anonym', 'creatExpParameter', '__package__', 'isdir', 'revivification', 'exit', '__loader__', 'makedirs', 'datetime', 'consult_db', 'Paragraph', '__cached__', '__builtins__', 'AutoVivification', 'getSampleStyleSheet', 'unvivification', 'rlcompleter', 'logging', 'verSofts', 'dico2txt']

Traceback (most recent call last):

File "/data_1/IRM/amigo/src/IRMAGE_python_modules/IRMAGE_dataGestion.py", line 206, in consult_db

print('keys2:', keys2)

NameError: name 'keys2' is not defined

所以...即使我们在exec()函数中将keys2定义为全局变量,它也不在全局范围内,因为在exec()函数之后返回globals()……我承认有些事情让我很想念。 ..

解决方案

Note: The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.

You can't create new local variables with exec on Python 3. Local variable lookup completely ignores the attempt.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值