Python基礎講座 #5 IPython

読了 4分

今回の講座では、IPythonシェルについて見ていきましょう。

Pythonの勉強をしたりコーディングをするとき、簡単なコードのテストをするためにPythonシェルをよく使うことになります。 Pythonシェルとは、Pythonインタプリタをインタラクティブモードで使えるアプリケーションです。Windowsのコマンドや、macOS、Linuxのターミナルを使うのと似ていると考えてください。JavaScriptで開発したことのある方であれば、JavaScriptコンソールと同じだと思ってもらえれば良いです。 Anaconda Pythonをインストールしていれば、IPythonはすでにインストールされているはずです。 もし通常のPythonをインストールしている場合は、次のコマンドで簡単にインストールできます。

pip install ipython もしAnaconda Pythonをインストールしたい方は、Python基礎講座 #2 Pythonをインストールしようをご覧ください。

それでは、IPythonシェルの使い方を見ていきましょう。 まずPythonの基本シェルをお見せしてから、IPythonシェルをお見せします。

コマンドを実行した後、pythonと入力します。 macOSやLinuxを使っている場合は、ターミナルで実行してください。

OSにインストールされているPythonバージョンが出力されながら、Pythonシェルが起動しました。

Hello Worldという文字列を出力するコードを入力してみましょう。

>>> print('Hello World!')
Hello World!

変数を定義して、変数に保存された値を出力してみましょう。

>>> myvar = 'This is myvar variable'
>>> print(myvar)
This is myvar variable

PythonライブラリからOSモジュールをインポートして、現在のフォルダ位置を出力してみましょう。

>>> import os
>>> os.getcwd()
'C:\\\\Users\\\\Curtis'

今回は for 文を使用してみます。

>>> for i in range(10):
...   print(i)
...
0
1
2
3
4
5
6
7
8
9

このようにPythonシェルを使えば、簡単なコードをソースファイルに保存して実行する必要なく、簡単に実行できます。

今度は、通常のPythonシェルとIPythonの違いについて見ていきましょう。

コマンドプロンプトでipythonと入力します。 ipythonシェルが起動しました。 先ほど通常のPythonシェルで実行したコードを実行してみましょう。

In [1]: print('Hello World!')
Hello World!

通常のPythonシェルとは違い、コードの可読性を高めるコードハイライティング機能を提供します。

通常のPythonシェルでは提供されない便利なタブコンプリーション機能を提供します。

In [2]: myvar = 'This is myvar variable'
In [3]: print(myvar)
This is myvar variable

モジュールに含まれているすべての関数を見ることもできます。

In [4]: import os
In [5]: os.getcwd()
Out[5]: 'D:\\\\OneDrive\\\\Projects\\\\Python Tutorials\\\\tutorial 5'

クエスチョンマークを使ってモジュールについての説明や、関数またはメソッドについての説明を参照することもできます。

In [6]: os?
Type:        module
String form: <module 'os' from 'C:\\\\Users\\\\CURTIS\\\\anaconda3\\\\lib\\\\os.py'>
File:        c:\\users\\curtis\\anaconda3\\lib\\os.py
Docstring:
OS routines for NT or Posix depending on what system we're on.

This exports:
- all functions from posix or nt, e.g. unlink, stat, etc.
- os.path is either posixpath or ntpath
- os.name is either 'posix' or 'nt'
- os.curdir is a string representing the current directory (always '.')
- os.pardir is a string representing the parent directory (always '..')
- os.sep is the (or a most common) pathname separator ('/' or '\\\\')
- os.extsep is the extension separator (always '.')
- os.altsep is the alternate pathname separator (None or '/')
- os.pathsep is the component separator used in $PATH etc
- os.linesep is the line separator in text files ('\\r' or '\\n' or '\\r\\n')
- os.defpath is the default search path for executables
- os.devnull is the file path of the null device ('/dev/null', etc.)

Programs that import and use 'os' stand a better chance of being
portable between different platforms.  Of course, they must then
only use functions that are defined by all platforms (e.g., unlink
and opendir), and leave all pathname manipulation to os.path
(e.g., split and join).

In [7]: os.getcwd?
Signature: os.getcwd()
Docstring: Return a unicode string representing the current working directory.
Type:      builtin_function_or_method

最後に、IPythonが提供するマジック関数の中からいくつかを見て、今回の講座を終わりにしましょう。 マジック関数を使うと、Pythonモジュールをインポートして行う必要があるものを簡単に解決できます。 まず、現在のフォルダのファイルをリスティングしてみましょう。 今度はtestという新しいフォルダを作って、testフォルダに移動してみましょう。 このほかにも本当に便利なマジック関数を多く提供していますが、マジック関数のリストは次のコマンドで出力できます。

In [18]: %quickref

IPython -- An enhanced Interactive Python - Quick Reference Card
================================================================

obj?, obj??      : Get help, or more help for object (also works as
?obj, ??obj).
?foo.*abc*       : List names in 'foo' containing 'abc' in them.
%magic           : Information about IPython's 'magic' % functions.

Magic functions are prefixed by % or %%, and typically take their arguments
without parentheses, quotes or even commas for convenience.  Line magics take a
single % and cell magics are prefixed with two %%.

Example magic function calls:

%alias d ls -F   : 'd' is now an alias for 'ls -F'
alias d ls -F    : Works if 'alias' not a python name
alist = %alias   : Get list of aliases to 'alist'
cd /usr/share    : Obvious. cd -<tab> to choose from visited dirs.
%cd??            : See help AND source for magic %cd
%timeit x=10     : time the 'x=10' statement with high precision.
%%timeit x=2**100
x**100           : time 'x**100' with a setup of 'x=2**100'; setup code is not
counted.  This is an example of a cell magic.

System commands:

!cp a.txt b/     : System command escape, calls os.system()
cp a.txt b/      : after %rehashx, most system commands work without !
---Return to continue, q to quit---

先にも申し上げた通り、Pythonシェルは開発をするときにコードのテストやモジュールのテストなどによく使われ、勉強しながらも簡単にコードをテストできる便利なツールなので、ぜひ慣れておいてください。 ここで今回の講座を終わり、次の講座ではJupyter Notebookについて見ていきましょう。

X