Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在exec内部导入的print_函数不会影响以后的代码_Python_Exec - Fatal编程技术网

Python 在exec内部导入的print_函数不会影响以后的代码

Python 在exec内部导入的print_函数不会影响以后的代码,python,exec,Python,Exec,(Python 2.7)通常,当我执行Python语句时,全局dict在执行后处于更新状态。例如,在下面的代码中,numpy将在执行后以全局形式显示,我可以继续使用它。但是,print\u功能的行为不同。针对locals和globals的成员资格测试都失败了,但我可以看到它并使用它,并且print仍然像python2print语句一样工作。这不一定是我想避免的,但我想了解更多。为什么会这样 exec(""" from __future__ import print_function import

(Python 2.7)通常,当我执行Python语句时,全局dict在执行后处于更新状态。例如,在下面的代码中,
numpy
将在执行后以全局形式显示,我可以继续使用它。但是,
print\u功能的行为不同。针对
locals
globals
的成员资格测试都失败了,但我可以看到它并使用它,并且print仍然像python2print语句一样工作。这不一定是我想避免的,但我想了解更多。为什么会这样

exec("""
from __future__ import print_function
import numpy

# prints "haha hoho"
print("haha", "hoho")
""")

# Executes without an error.
print(numpy.zeros((2, 2)))

# Prints "('haha', 'hoho')". (why?)
print("haha", "hoho")

# No error. (why?)
print 'haha'

# Both print False.
print(print_function in globals())
print(print_function in locals())

# However, this prints without an error.
print(print_function)             
更新:

我犯了一个错误,会员资格测试应该使用以下名称:

# Now both print True
print("print_function" in globals())
print("print_function" in locals())
将来的导入结果是一个特殊的future语句,这导致编译(在执行
exec
语句时)生成不同的代码。因此,它只影响由相应的
exec
语句编译的代码的执行

更新:

事实证明,在交互式解释器中,例如笔记本的单元格,future语句的效果超出了单元格边界。但是,如果单元格中存在
exec
语句,则
exec
中的未来语句仍然只影响要执行的代码