IPython:標準のPythonシェルを置き換える

Pythonシェルは、言語の機能をテストおよび調査するのに非常に便利なものです。誰かがそれを計算機として使用することもあります(偶然ですが、非常に便利です)。作業をより効果的にする機能のリスト。





公式サイトからIPythonをダウンロードしてインストールできます



名前空間



標準のPythonシェルでは変数に値を割り当てることができるため、コマンド「ipython」でIPythonシェルを開始します。

In [1]: msgflag = 1



In [2]: pi = 3



In [3]: msg = "hello"



In [4]: warning = None







入力中に、たとえばmsgと入力してTabを押すことにより、オートコンプリートを使用できます。次のオプションがあります。

In [5]: msg

msg msgflag







オプションが1つしかない場合は、入力フィールドに自動的に表示されます。



IPythonは名前空間を使用する機能を提供します。たとえば、whoコマンドは使用可能な変数のリストを表示します。

In [5]: who

msg msgflag pi warning







たとえば、int型の変数を表示するには、次のように記述する必要があります。

In [6]: who int

msgflag pi







変数に関する詳細情報が必要な場合は、「whos」コマンドを使用できます。

 In [7]: whos Variable Type Data/Info -------------------------------- msg str hello msgflag int 1 pi int 3 warning NoneType None
      
      





変数名で検索することもできます。そのためには、「psearch」コマンドを使用する必要があります。

In [8]: psearch msg*

msg

msgflag







次の例のように、変数タイプを使用して検索条件を拡張できます。

In [9]: psearch msg* int

msgflag







プロファイルに変数を保存するために(IPythonの再起動後に使用可能になります)、「ストア」コマンドがあります。

In [10]: store msgflag

Stored 'msgflag' (int)







変数を別のファイルに保存することもできます。

In [11]: store msgflag > /tmp/m.txt

Writing 'msgflag' (int) to file '/tmp/m.txt'.







保存された変数を表示するには、パラメーターなしで「store」コマンドを入力します。

In [12]: store

Stored variables and their in-db values:

msgflag -> 1







現在のネームスペースをクリアするには、「reset」コマンドを使用し、「who」コマンドを使用してクリアされていることを確認します。

In [13]: reset

Once deleted, variables cannot be recovered. Proceed (y/[n])? y



In [14]: who

Interactive namespace is empty.







「store」コマンドを使用して以前に保存された変数を復元し、「who」コマンドで復元されたことを確認できます。

In [15]: store -r



In [16]: who

msgflag







また、ストア内にあるすべてのものをクリアすることもでき、次の開始時に名前空間は空になります。

In [17]: store -z







ロギング



IPythonのもう1つの便利な機能はロギングです。 'logstate'コマンドは、ロガーの現在の状態を確認します。

In [18]: logstate

Logging has not been activated.







logstartコマンドはロギングを開始できます。

In [19]: logstart

Activating auto-logging. Current session state plus future input saved.

Filename : ipython_log.py

Mode : rotate

Output logging : False

Raw input log : False

Timestamping : False

State : active







ログは、Pythonソースコードとして現在のディレクトリに保存されます。

コマンド 'logon'および 'logoff'は、ロギングを有効/無効にするために使用されます。

In [20]: logoff

Switching logging OFF



In [21]: logon

Switching logging ON







マジックチーム



上記のIPython用語で説明されているコマンドは、マジックコマンドと呼ばれます。 マジックコマンドの完全なリストを表示するには、「lsmagic」と入力する必要があります。

In [22]: lsmagic

Available magic functions:

%Exit %Pprint %Quit %alias %autocall %autoindent %automagic %bg %bookmark %cd %clear %color_info %colors %cpaste %debug %dhist %dirs %doctest_mode %ed %edit %env %exit %hist %history %logoff %logon %logstart %logstate %logstop %lsmagic %macro %magic %p %page %pdb %pdef %pdoc %pfile %pinfo %popd %profile %prun %psearch %psource %pushd %pwd %pycat %quickref %quit %r %rehash %rehashx %rep %reset %run %runlog %save %sc %store %sx %system_verbose %time %timeit %unalias %upgrade %who %who_ls %whos %xmode



Automagic is ON, % prefix NOT needed for magic functions.







マジックチームは、パーセント記号をプレフィックスとして使用できます。 これは、変数名がコマンド名と一致する場合に便利です。

すべてのマジックコマンドのヘルプを呼び出すには、 'magic'コマンドを使用します。 特定の魔法のコマンドに関するヘルプを表示するには、最後に疑問符を付けてください:

In [23]: lsmagic?

Type: Magic function

Base Class: <type 'instancemethod'>

String Form: <bound method InteractiveShell.magic_lsmagic of <IPython.iplib.InteractiveShell object at 0x9e5ef0>>

Namespace: IPython internal

File: /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/ipython-0.9.1-py2.5.egg/IPython/Magic.py

Definition: lsmagic(self, parameter_s='')

Docstring:

List currently available magic functions.







詳細については、コマンドの最後に疑問符を2つ入力してください。その場合、機能コマンドのソースコードも表示されます。



独立して定義された変数の場合、疑問符も使用できます。

In [24]: msgflag?

Type: int

Base Class: <type 'int'>

String Form: 1

Namespace: Interactive

Docstring:

int(x[, base]) -> integer



Convert a string or number to an integer, if possible. A floating point

argument will be truncated towards zero ...







一部の「化粧品」チーム



「print」の省略形として「p」を使用できます。

In [25]: import sys



In [26]: p sys.path

['', '/Library/Frameworks/Python.framework/Versions/2.5/bin', '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg', '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/bdist_mpkg-0.4.3-py2.5.egg', '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/macholib-1.1-py2.5.egg',

...









短い形式を使用して関数を呼び出すこともできます。

In [27]: def x(a, b):

....: print a, b

....:

....:



In [28]: x 3, 4

-------> x(3, 4)

3 4









関数を呼び出すには、次を実行できます。

In [29]: def x(): print "123"

....:



In [30]: /x

-------> x()

123









文字列を引用符で囲む必要なく、パラメータとして文字列を受け取る関数を呼び出すことができます。

In [31]: def x(a,b): print "%s-%s" % (a, b)

....:



In [32]: , x astr bstr

-------> x("astr", "bstr")

astr-bstr







内省



関数またはメソッドを呼び出すために必要な引数を忘れた場合は、「pdef」コマンドでいつでも確認できます。

In [37]: import re



In [38]: pdef re.match

re.match(pattern, string, flags=0)









この関数のドキュメントもご覧ください。

In [39]: pdoc re.match

Class Docstring:

Try to apply the pattern at the start of the string, returning

a match object, or None if no match was found.

Calling Docstring:

x.__call__(...) <==> x(...)









関数に関するすべての情報は、「pinfo」コマンドを使用して表示できます。

In [40]: pinfo re.match

Type: function

Base Class: <type 'function'>

String Form: <function match at 0xaa2b70>

Namespace: Interactive

File: /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/re.py

Definition: re.match(pattern, string, flags=0)

Docstring:

Try to apply the pattern at the start of the string, returning

a match object, or None if no match was found.









関数のソースコードも確認できます。

In [41]: psource re.match

def match(pattern, string, flags=0):

"""Try to apply the pattern at the start of the string, returning

a match object, or None if no match was found."""

return _compile(pattern, flags).match(string)









このオブジェクトまたはそのオブジェクトが定義されているファイルのソースコードを表示するには、「pfile」コマンドを使用します。

In [42]: pfile re.match









お気に入りのエディターを起動して、このオブジェクトまたはそのオブジェクトが定義されているファイルを編集することもできます。

In [43]: edit -x re.match

Editing...







ソースへの参照



スクリーンキャスト-http : //showmedo.com/videos/video ? name=1000010&fromSeriesID= 100

公式ドキュメント-http://ipython.scipy.org/moin/Documentation



PS:今のところこれで終わりです。このトピックが誰にとっても興味深いものである場合は、次の記事で引き続きIPythonの機能について説明します。



All Articles