コマンドラインでのPython

シェルでのデータ処理

Susan Sun

Data Person

Pythonの基本

Python

  • MacOS, Linuxには標準搭載
  • Windowsはユーザーがインストール(手順)
  • GUI(例: Jupyter Notebook, Spyder, PyCharm など)で使用可能
  • コマンドラインから直接利用も可能
シェルでのデータ処理

Pythonドキュメントの利用

ドキュメント:

man python
...
-V ,  --version 
    Prints the Python version number of the executable and exits.
python --version
Python 3.5.2
シェルでのデータ処理

Pythonドキュメントの利用

例: ネイティブのPythonを使用

which python
/usr/bin/python
シェルでのデータ処理

Pythonの対話セッション

ターミナルで対話セッションを開始:

python
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linuxType "help", "copyright", "credits" or 
"license" for more information.
>>>
シェルでのデータ処理

Pythonの対話セッション

対話セッション内ではPython構文のみを使用:

>>> print('hello world')
hello world

Pythonを終了してターミナルに戻る:

>>> exit()
$
シェルでのデータ処理

対話セッションの代替

Pythonの対話セッション:

  • 起動が簡単で直感的
  • 再現性には不向き

代替:

  • Pythonのコマンドを.pyスクリプトに保存
  • python + スクリプト名で実行
シェルでのデータ処理

コマンドラインでのPythonスクリプト実行

方法1

  • コマンドラインのテキストエディタ(例: nano, Vim, Emacs)で.pyファイルを作成

暗いターミナルでnanoエディタのスクリーンショット

シェルでのデータ処理

コマンドラインでのPythonスクリプト実行

方法2

  • echoでPython文をhello_world.pyに書き込み、同時にファイルを作成
echo "print('hello world')" > hello_world.py

ファイル内容を確認:

cat hello_world.py
print('hello world')
シェルでのデータ処理

コマンドラインでのPythonスクリプト実行

.pyファイルと同じディレクトリにいることを確認:

ls
hello_world.py

ファイル名の前にpythonを付けて実行:

python hello_world.py
hello world
シェルでのデータ処理

練習しましょう!

シェルでのデータ処理

Preparing Video For Download...