Skip to content

Latest commit

 

History

History
35 lines (26 loc) · 609 Bytes

16.md

File metadata and controls

35 lines (26 loc) · 609 Bytes
@author jackzhenguo
@desc 
@date 2019/2/15

16 执行字符串表示的代码

将字符串编译成python能识别或可执行的代码,也可以将文字读成字符串再编译。

In [1]: s  = "print('helloworld')"
    
In [2]: r = compile(s,"<string>", "exec")
    
In [3]: r
Out[3]: <code object <module> at 0x0000000005DE75D0, file "<string>", line 1>
    
In [4]: exec(r)
helloworld

s  = """
def f():
    a = 100 % 52
    print(a)
f()
"""
r = compile(s,"<string>", "exec")
exec(r)

输出 48

[上一个例子](15.md) [下一个例子](17.md)