3
是從更復雜的代碼庫中提取這個簡單的Python程序:檢查拉姆達代碼
#insp.py
import inspect
L = lambda x: x+1
print("L(10)=" + str(L(10)))
code = inspect.getsource(L)
print(code)
作品,如果我在命令行中運行它:
$ python insp.py
如果我複製和粘貼python解釋器中的每行失敗:
d:\>python
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import inspect
>>> L = lambda x: x+1
>>> print("L(10)=" + str(L(10)))
L(10)=11
>>> code = inspect.getsource(L)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "d:\Users\Cimino\AppData\Local\Programs\Python\Python35-32\Lib\inspect.py", line 944, in getsource
lines, lnum = getsourcelines(object)
File "d:\Users\Cimino\AppData\Local\Programs\Python\Python35-32\Lib\inspect.py", line 931, in getsourcelines
lines, lnum = findsource(object)
File "d:\Users\Cimino\AppData\Local\Programs\Python\Python35-32\Lib\inspect.py", line 762, in findsource
raise OSError('could not get source code')
OSError: could not get source code
請注意,使用IPython而不是普通的Python解釋器,它的工作原理!
有人知道爲什麼嗎?
我在Windows7下使用Python 3.5 32位。
我想這是因爲檢查模塊實際上去尋找解釋器跟蹤的源文件。注意接口也可以給你行號,定義之前的註釋等。當你在REPL中時,這些都不存在。我想象IPython會做一些魔術來確保在交互式案例中檢查能夠正常工作。 – pvg