Python exec statement

Overview

python


exec <Code to execute> [Dictionary of reference variables[,Dictionary of variable allocation destination]]

Example

exec.py


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



##Basic example. There are side effects in the global environment
exec "x=1"
print "x in global env is", x


##Run in your own environment.
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"]



##Run in your own environment. Variable assignment to another environment
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"]

Execution result

python


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

Recommended Posts

Python exec statement
Python if statement
[Python] if statement
Python assert statement
Python basics ② for statement
Python basic if statement
[Python] for statement error
Python
Addition with Python if statement
[Python / PyQ] 4. list, for statement
[Python] What is a with statement?
Python Exercise for Beginners # 2 [for Statement / While Statement]
python sql statement extracted by time
Python for statement ~ What is iterable ~
[python] Correct usage of if statement
[Python] Multiplication table using for statement
Python --Difference between exec and eval
[Python] File operation using if statement
kafka python
Python basics ⑤
python + lottery 6
Built-in python
Python comprehension
Python technique
[Python] Super easy test with assert statement
Studying python
Python 2.7 Countdown
Python memorandum
Python FlowFishMaster
Python service
[Introduction to Udemy Python3 + Application] 33. if statement
python function ①
Python basics
Python memo
ufo-> python (3)
Python comprehension
install python
Python Singleton
Python basics ④
Python Memorandum 2
python memo
Python Jinja2
Python increment
python tips
Installing Python 3.4.3.
Try python
Python memo
Python iterative
Python algorithm
[Python] Variables
Python functions
Python sys.intern ()
Python decimals
python underscore
Python summary
Start python
[Python] Sort
Note: Python
Python basics ③
Python basics
return statement