V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
oh8
V2EX  ›  Python

关于 python 3 exec 的问题

  •  
  •   oh8 · 2016-09-18 09:26:01 +08:00 · 2197 次点击
    这是一个创建于 2788 天前的主题,其中的信息可能已经有所发展或是发生改变。

    python 3 的 exec 如果在方法内执行, exec 的代码中定义的变量好像无法被读取到?

    比如下面这代码

    def test():
    	code = "x = 999"
    	exec(code)
    	print(x)
    
    if __name__ == '__main__':
    	test()
    

    在 python2 中可以正确运行,输出 999 ,但在 python 3 中就会出现 NameError: name 'x' is not defined 。

    但如果不放在方法内,比如

    if __name__ == '__main__':
    	code = "x = 999"
    	exec(code)
    	print(x)
    

    python 2 和 3 就都可以正确运行。

    所以问题是:如何在 python 3 中,在方法( func )内,得到 exec(code) 里面所定义的变量?

    5 条回复    2016-09-18 15:28:45 +08:00
    qinxg
        1
    qinxg  
       2016-09-18 09:45:12 +08:00   ❤️ 1
    exec 中的变量 作用域的问题吧
    不懂 python 瞎猜的
    mgna17
        2
    mgna17  
       2016-09-18 09:53:04 +08:00   ❤️ 2
    oh8
        3
    oh8  
    OP
       2016-09-18 10:23:12 +08:00
    @mgna17 正解了, thanks
    thisisx7
        4
    thisisx7  
       2016-09-18 15:25:48 +08:00
    我在 python3 中做了这样一个实验
    http://imgur.com/a/iFa7P

    发现已经写进了作用域里面可是为什么不生效呢?
    后来在  stackoverflow 里面发现了这个的讨论
    在  python3  里面,  python 进行了优化
    http://stackoverflow.com/questions/25076883/creating-dynamically-named-variables-in-a-function-in-python-3-understanding-e
    thisisx7
        5
    thisisx7  
       2016-09-18 15:28:45 +08:00
    附上图片

    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1073 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 22:23 · PVG 06:23 · LAX 15:23 · JFK 18:23
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.