4
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

Pythonのexec文

概要

exec <実行するコード> [参照変数の辞書 [, 変数割当先の辞書]]

exec.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-



## 基本の例。グローバル環境に副作用あり
exec "x=1"
print "x in global env is", x


## 独自環境で実行する。
ref1=dict(x=100)
exec """print 'x in temporary env is', x
y=x+1""" in ref1
print "y is in global()? ->", "y" in globals()
print "y in ref1 is", ref1["y"]



## 独自環境で実行する。変数の割当は、別環境に
ref2=dict(x=1000)
dest=dict()
exec "z=1+x" in ref2, dest
print "z is in global()? ->", "z" in globals()
print "z is in ref2? ->", "z" in ref2
print "z in dest is", dest["z"]

実行結果

bash-3.2$ ./exec.py 
x in global env is 1
x in temporary env is 100
y is in global()? -> False
y in ref1 is 101
z is in global()? -> False
z is in ref2? -> False
z in dest is 1001
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
4
Help us understand the problem. What are the problem?