python3 compile_Python3 compile()函数

1.Python3 compile()函数

exec 语句或者内建函数eval()来执行这些对象或者对它们进行求值。

一个很重要的观点是:

第一参数代表了要编译的

可求值表达式:

Python

>>> eval_code = compile('100 + 200', '', 'eval')

>>> eval(eval_code)

300

1

2

3

>>>eval_code=compile('100 + 200','','eval')

>>>eval(eval_code)

300

可执行语句组:

Python

>>> exec_code = compile("""

... req = input('Count how many numbers? ')

... for eachNum in range(req):

... print eachNum

... """, '', 'exec')

>>> exec exec_code

Count how many numbers? 6

0

1

2

3

4

5

1

2

3

4

5

6

7

8

9

10

11

12

13

>>>exec_code=compile("""

... req = input('Count how many numbers? ')

... for eachNum in range(req):

... print eachNum

... """,'','exec')

>>>execexec_code

Counthowmanynumbers?6

0

1

2

3

4

5

2.eval函数

eval()对表达式求值,后者可以为字符串或内建函数complie()创建的预编译代码对象。

eval(source[, globals[, locals]])

第二个和第三个参数,都为可选的,分别代表了全局和局部名字空间中的对象。如果给出这两个参数,globals 必须是个字典,locals可以是任意的映射对象,比如,一个实现了__getitem__()方法的对象。(在2.4 之前,local 必须是一个字典)如果都没给出这两个参数,分别默认为globals()和locals()返回的对象,如果只传入了一个全局字典,那么该字典也作为locals 传入。

Python

>>> eval('100 + 200')

300

1

2

>>>eval('100 + 200')

300

3.exec语句

exec 语句执行代码对象或字符串形式的

Python

>>> exec """

... x = 0

... print 'x is currently:', x

... while x < 5:

... x += 1

... print 'incrementing x to:', x

... """

x is currently: 0

incrementing x to: 1

incrementing x to: 2

incrementing x to: 3

incrementing x to: 4

incrementing x to: 5

1

2

3

4

5

6

7

8

9

10

11

12

13

>>>exec"""

... x = 0

... print 'x is currently:', x

... while x < 5:

... x += 1

... print 'incrementing x to:', x

... """

xiscurrently:0

incrementingxto:1

incrementingxto:2

incrementingxto:3

incrementingxto:4

incrementingxto:5

最后, exec 还可以接受有效的python 文件对象。如果我们用上面的多行代码创建一个叫xcount.py 的文件,那么也可以用下面的方法执行相同的代码

Python

>>> f = open('xcount.py') # open the file

>>> exec f # execute the file

x is currently: 0

incrementing x to: 1

incrementing x to: 2

incrementing x to: 3

incrementing x to: 4

incrementing x to: 5

1

2

3

4

5

6

7

8

>>>f=open('xcount.py')# open the file

>>>execf# execute the file

xiscurrently:0

incrementingxto:1

incrementingxto:2

incrementingxto:3

incrementingxto:4

incrementingxto:5

2018-05-29-012523.png

2020012309512985.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值