推荐学习书目
› 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 · Sep 18, 2016 · 3354 views
    This topic created in 3661 days ago, the information mentioned may be changed or developed.

    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 replies  •  2016-09-18 15:28:45 +08:00
    qinxg
        1
    qinxg  
       Sep 18, 2016   ❤️ 1
    exec 中的变量 作用域的问题吧
    不懂 python 瞎猜的
    mgna17
        2
    mgna17  
       Sep 18, 2016   ❤️ 2
    oh8
        3
    oh8  
    OP
       Sep 18, 2016
    @mgna17 正解了, thanks
    thisisx7
        4
    thisisx7  
       Sep 18, 2016
    我在 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  
       Sep 18, 2016
    附上图片

    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2538 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 10:31 · PVG 18:31 · LAX 03:31 · JFK 06:31
    ♥ Do have faith in what you're doing.