LoginSignup
4
4

More than 5 years have passed since last update.

Pythonのexec文

Posted at

概要

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
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4