2016-12-06 10 views
3

この単純なPythonプログラムをラムダコードを点検し、私がコピーした場合Pythonインタプリタから、より複雑なコードベースから抽出された

$ 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 

プレーンなPythonインタプリタ、それは動作します!

なぜ誰が知っていますか?

私は、Windows7ではPython 3.5 32ビットを使用します。

+0

これは、inspectモジュールが実際に行って、インタプリタが追跡するソースファイルを探すためです。インターフェイスには、行番号、定義の前のコメントなども表示できることに注意してください。REPLに入っているときは、これらのどれも存在しません。 IPythonはインタラクティブなケースでinspectが正しく動作するようにいくつかの魔法を使っていると思います。 – pvg

答えて

2

これは、linecacheモジュールを使用して入力したすべてのコマンドをキャッシュするため、IPythonで機能します。例えば

$ ipy ## Equivalent to ipython --classic 
Python 2.7.10 (default, Jul 30 2016, 18:31:42) 
Type "copyright", "credits" or "license" for more information. 

IPython 3.0.0 -- An enhanced Interactive Python. 
?   -> Introduction and overview of IPython's features. 
%quickref -> Quick reference. 
help  -> Python's own help system. 
object? -> Details about 'object', use 'object??' for extra details. 
>>> print a 
Traceback (most recent call last): 
    File "<ipython-input-1-9d7b17ad5387>", line 1, in <module> 
    print a 
NameError: name 'a' is not defined 

お知らせここ<ipython-input-1-9d7b17ad5387>部分、これはIPythonに固有のものです。

$ python 
Python 2.7.10 (default, Jul 30 2016, 18:31:42) 
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> print a 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
NameError: name 'a' is not defined 

今度は、あなたのコードを実行してみましょう:Lに関連するファイル名を見つけるために

>>> import inspect 
>>> L = lambda x: x+1 
>>> code = inspect.getsource(L) 

時間:

>>> L.func_code.co_filename 
'<ipython-input-2-0c0d6f325784>' 

は今場合を見てみましょう通常のPythonであなたが<stdin>を見るでしょうシェルこのファイルのソースはlinecache.cacheです。

>>> import linecache 
>>> linecache.cache[L.func_code.co_filename] 
(18, 1481047125.479239, [u'L = lambda x: x+1\n'], '<ipython-input-2-0c0d6f325784>') 

この情報を使用すると、IPythonは必要なソースを見つけることができますが、Pythonシェルは格納していないため、このソースは見つかりません。


inspectはソースを取得する方法についての関連の詳細は、ソースコードにgetsourcefilefindsource機能で見つけることができます。

関連する問題