在命令列使用 Python

在 Shell 中進行資料處理

Susan Sun

Data Person

Python 基礎

Python

  • MacOS、Linux 已預先安裝
  • Windows 需自行安裝(說明在此
  • 可搭配 GUI 介面使用(如 Jupyter Notebook、Spyder、PyCharm 等)
  • 也可直接透過命令列介面存取
在 Shell 中進行資料處理

使用 Python 文件

文件:

man python
...
-V ,  --version 
    Prints the Python version number of the executable and exits.
python --version
Python 3.5.2
在 Shell 中進行資料處理

使用 Python 文件

範例:使用系統內建的 Python

which python
/usr/bin/python
在 Shell 中進行資料處理

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.
>>>
在 Shell 中進行資料處理

Python 互動式環境

在互動式環境內只能用 Python 語法:

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

離開 Python 回到終端機:

>>> exit()
$
在 Shell 中進行資料處理

互動式環境的替代方案

Python 互動式環境

  • 啟動容易,直覺好用
  • 不利程式碼重現

替代作法

  • 將指令存成 .py 腳本
  • python + 檔名 執行腳本
在 Shell 中進行資料處理

在命令列執行 Python 腳本

方法 1

  • 用命令列文字編輯器建立 .py 檔(如 nano、Vim、Emacs)

深色終端機視窗中的 nano 文字編輯器螢幕截圖

在 Shell 中進行資料處理

在命令列執行 Python 腳本

方法 2

  • echo 將 Python 語法寫入 hello_world.py,同時建立檔案。
echo "print('hello world')" > hello_world.py

檢查檔案內容:

cat hello_world.py
print('hello world')
在 Shell 中進行資料處理

在命令列執行 Python 腳本

確認你與 .py 檔在同一資料夾:

ls
hello_world.py

python 加檔名來執行 .py 檔:

python hello_world.py
hello world
在 Shell 中進行資料處理

一起來練習吧!

在 Shell 中進行資料處理

Preparing Video For Download...