eval函数仅仅允许执行简单的表达式。对于更大的代码块时,使用compileexec函数。

例子:使用 compile函数验证语法

NAME = "script.py"

BODY = """
prnt 'owl-stretching time'
""" try:
compile(BODY, NAME, "exec")
except SyntaxError, v:
print "syntax error:", v, "in", NAME

结果如下:

syntax error: invalid syntax in script.py

当成功时,compile函数返回一个代码对象,你能够使用exec来执行他。

BODY = """
print 'the ant, an introduction'
""" code = compile(BODY, "<script>", "exec") print code exec code

结果如下:

<code object ? at 8c6be0, file "<script>", line 0>
the ant, an introduction

为了能够快速的生成代码,你可以使用下面例子中的类。使用write方法来添加状态,indent和**dedent **来添加结构,这个类能够方便的让其他类进行调用。

import sys, string

class CodeGeneratorBackend:
"Simple code generator for Python" def begin(self, tab="\t"):
self.code = []
self.tab = tab
self.level = 0 def end(self):
self.code.append("") # make sure there's a newline at the end
return compile(string.join(self.code, "\n"), "<code>", "exec") def write(self, string):
self.code.append(self.tab * self.level + string) def indent(self):
self.level += 1
# in Python 1.5.2 and earlier, use this instead:
# self.level = self.level + 1 def dedent(self):
if self.level == 0:
raise SyntaxError, "internal error in code generator"
self.level -= 1
# in Python 1.5.2 and earlier, use this instead:
# self.level = self.level - 1 #
# try it out! c = CodeGeneratorBackend()
c.begin()
c.write("for i in range(5):")
c.indent()
c.write("print 'code generation made easy!'")
c.dedent()
exec c.end()

结果如下:

code generation made easy!
code generation made easy!
code generation made easy!
code generation made easy!
code generation made easy!

python也提供了execfile的函数,他能够方便的从文件中加载代码,并编译和执行。如下的例子是如何使用这个函数。

execfile("hello.py")

def EXECFILE(filename, locals=None, globals=None):
exec compile(open(filename).read(), filename, "exec") in locals, globals EXECFILE("hello.py")

结果如下:

hello again, and welcome to the show
hello again, and welcome to the show

在这个例子中 hello.py的代码如下:

print "hello again, and welcome to the show"

从__builtin__ 的模块中重载函数。

因为python是在验证局部和模块名称空间后才进行查看内建函数,在这种情况下你需要特别的引用__builtin__ 模块。在如下的例子脚本中,重载open一个版本函数,这个版本中能够打开一个普通文件验证是不是以一个“特殊”的字符串开始。为了能够使用原始的open函数,需要明确的引用模块名称。

def open(filename, mode="rb"):
import __builtin__
file = __builtin__.open(filename, mode)
if file.read(5) not in("GIF87", "GIF89"):
raise IOError, "not a GIF file"
file.seek(0)
return file fp = open("samples/sample.gif")
print len(fp.read()), "bytes" fp = open("samples/sample.jpg")
print len(fp.read()), "bytes"

结果如下:

3565 bytes
Traceback (innermost last):
File "builtin-open-example-1.py", line 12, in ?
File "builtin-open-example-1.py", line 5, in open
IOError: not a GIF file

转载请标明来之:http://www.bugingcode.com/

更多教程:阿猫学编程

python标准库-builtin 模块之compile,execfile的更多相关文章

  1. [python标准库]Pickle模块

    Pickle-------python对象序列化 本文主要阐述以下几点: 1.pickle模块简介 2.pickle模块提供的方法 3.注意事项 4.实例解析 1.pickle模块简介 The pic ...

  2. Python 标准库 ConfigParser 模块 的使用

    Python 标准库 ConfigParser 模块 的使用 demo #!/usr/bin/env python # coding=utf-8 import ConfigParser import ...

  3. Python标准库——collections模块的Counter类

    1.collections模块 collections模块自Python 2.4版本开始被引入,包含了dict.set.list.tuple以外的一些特殊的容器类型,分别是: OrderedDict类 ...

  4. [python标准库]XML模块

    1.什么是XML XML是可扩展标记语言(Extensible Markup Language)的缩写,其中的 标记(markup)是关键部分.您可以创建内容,然后使用限定标记标记它,从而使每个单词. ...

  5. 【python】Python标准库defaultdict模块

    来源:http://www.ynpxrz.com/n1031711c2023.aspx Python标准库中collections对集合类型的数据结构进行了很多拓展操作,这些操作在我们使用集合的时候会 ...

  6. Python标准库--os模块

    这个模块包含普遍的操作系统功能.如果你希望你的程序能够与平台无关的话,这个模块是尤为重要的.即它允许一个程序在编写后不需要任何改动,也不会发生任何问题,就可以在Linux和Windows下运行.一个例 ...

  7. python标准库 bisect模块

    # -*- coding: utf-8 -*- # python:2.x __author__ = 'Administrator' #bisect #作用:维护有序列表,而不必在每次向列表增加一个元素 ...

  8. python标准库 sysconfig模块

    # -*- coding: utf-8 -*-# python:2.x__author__ = 'Administrator'import sysconfig#sysconfig:解释器编译时配置#作 ...

  9. Python标准库 -- UUID模块(生成唯一标识)

    UUID是什么: UUID: 通用唯一标识符 ( Universally Unique Identifier ),对于所有的UUID它可以保证在空间和时间上的唯一性,也称为GUID,全称为: UUID ...

随机推荐

  1. 从[Greenplum 6.0] 1分钟安装尝鲜开始

    Greenplum目前6版本目前已经迭代了几个小版本了,随着版本的更新,不断的有bug被修复. 打算试用的朋友可以入手了. 作为开年的第一个工作日的第一个帖子,必须从“开天辟地”的6.0开始.以下内容 ...

  2. Java static 静态代码块、代码块

    简述 static{} 静态代码块,加载类之前执行 {} 代码块,每次new的时候都会被执行 示例 类: public class Student { int age; String name; bo ...

  3. 刷题41. First Missing Positive

    一.题目说明 题目是41. First Missing Positive,求一个未排序队列中缺失的最小正整数.时间复杂度要求是O(n).难度是Hard,确实难. 二.我的解答 不考虑时间复杂度,首先对 ...

  4. opencv模板匹配查找图像(python)

    #!/usr/bin/env python3 # -*- coding: utf-8 -*- import cv2 import numpy as np from cv2 import COLOR_B ...

  5. ZJNU 1138 - 小兔的棋盘——中级

    二维图的动态规划因为不能穿越对角线,则选取对角线的一边dp即可选取对角线右下侧则x轴上每个点只能由其左侧的点走过去(只有1条)对角线上的点只能由对角线下方的点走过去其他点可以由左侧和下侧两种方式到达因 ...

  6. vs strcore.cpp(156) 内存泄漏

    在一个静态函数的线程回调中,一个cstring的对象没释放. 遇到这种问题: 1.查看所有的指针对象,有没有合适的回收 2.查看代码的malloc,看看有没有free 3.一点一点注释代码,定位位置

  7. C - Line-line Intersection Gym - 102220C(线段相交)

    There are n lines l1,l2,…,ln on the 2D-plane. Staring at these lines, Calabash is wondering how many ...

  8. 查看linux系统安装的服务

    如何查看linux系统安装了哪些服务呢,因不同版本的操作系统可能使用的命令不一样或者有些命令在某些操作系统不可用,现列举一些常用查看命令(基于我的linux版本). 我的操作系统版本如下: 1.ser ...

  9. EMCCD

    EMCCD 即电子倍增CCD,是探测领域内灵敏度极高的一种高端光电探测产品. 在光子探测领域的应用发展对探测器灵敏度的要求不断提高,EMCCD (Electron-Multiplying CCD)技术 ...

  10. Linux把内存挂载成硬盘提高读写速度

    tmpfs是一种虚拟内存文件系统正如这个定义它最大的特点就是它的存储空间在VM里面,这里提一下VM(virtual memory),VM是由linux内核里面的vm子系统管理,现在大多数操作系统都采用 ...