==code 模塊== ``code`` 模塊提供了一些用於模擬標准交互解釋器行為的函數. ``compile_command`` 與內建 ``compile`` 函數行為相似, 但它會通過測試來保證你傳遞的是一個完成的 Python 語句. 在 [Example 2-47 #eg-2-47] 中, 我們一行一行地編譯一個程序, 編譯完成后會執行所得到的代碼對象 (code object). 程序代碼如下: ``` a = ( 1, 2, 3 ) print a ``` 注意只有我們到達第 2 個括號, 元組的賦值操作能編譯完成. ====Example 2-47. 使用 code 模塊編譯語句====[eg-2-47] ``` File: code-example-1.py import code import string # SCRIPT = [ "a = (", " 1,", " 2,", " 3 ", ")", "print a" ] script = "" for line in SCRIPT: script = script + line + "\n" co = code.compile_command(script, "<stdin>", "exec") if co: # got a complete statement. execute it! print "-"*40 print script, print "-"*40 exec co script = "" *B*---------------------------------------- a = ( 1, 2, 3 ) ---------------------------------------- ---------------------------------------- print a ---------------------------------------- (1, 2, 3)*b* ``` //InteractiveConsole// 類實現了一個交互控制台, 類似你啟動的 Python 解釋器交互模式. 控制台可以是活動的(自動調用函數到達下一行) 或是被動的(當有新數據時調用 //push// 方法). 默認使用內建的 ``raw_input`` 函數. 如果你想使用另個輸入函數, 你可以使用相同的名稱重載這個方法. [Example 2-48 #eg-2-48] 展示了如何使用 ``code`` 模塊來模擬交互解釋器. ====Example 2-48. 使用 code 模塊模擬交互解釋器====[eg-2-48] ``` File: code-example-2.py import code console = code.InteractiveConsole() console.interact() *B*Python 1.5.2 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam (InteractiveConsole) >>> a = ( ... 1, ... 2, ... 3 ... ) >>> print a (1, 2, 3)*b* ``` [Example 2-49 #eg-2-49] 中的腳本定義了一個 ``keyboard`` 函數. 它允許你在程序中手動控制交互解釋器. ====Example 2-49. 使用 code 模塊實現簡單的 Debugging====[eg-2-49] ``` File: code-example-3.py def keyboard(banner=None): import code, sys # use exception trick to pick up the current frame try: raise None except: frame = sys.exc_info()[2].tb_frame.f_back # evaluate commands in current namespace namespace = frame.f_globals.copy() namespace.update(frame.f_locals) code.interact(banner=banner, local=namespace) def func(): print "START" a = 10 keyboard() print "END" func() *B*START Python 1.5.2 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam (InteractiveConsole) >>> print a 10 >>> print keyboard <function keyboard at 9032c8> ^Z END*b* ```
