eval函數僅僅容許執行簡單的表達式。對於更大的代碼塊時,使用compile和exec函數。python
例子:使用 compile函數驗證語法編程
NAME = "script.py" BODY = """ prnt 'owl-stretching time' """ try: compile(BODY, NAME, "exec") except SyntaxError, v: print "syntax error:", v, "in", NAME
結果以下:app
syntax error: invalid syntax in script.py
當成功時,compile函數返回一個代碼對象,你可以使用exec來執行他。函數
BODY = """ print 'the ant, an introduction' """ code = compile(BODY, "<script>", "exec") print code exec code
結果以下:ui
<code object ? at 8c6be0, file "<script>", line 0> the ant, an introduction
爲了可以快速的生成代碼,你能夠使用下面例子中的類。使用write方法來添加狀態,indent和dedent 來添加結構,這個類可以方便的讓其餘類進行調用。this
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
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的代碼以下:ip
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/
更多教程:阿貓學編程