2015/09/27

Raspberry Pi:安裝Python 3.5

Python 3.5於2015-09-13釋出,不再支援Windows XP,這篇要試試在Raspberry Pi 2 + Raspbian上安裝Python 3.5。

因為pip需要SSL,所以先安裝相關套件:
$ sudo apt-get install openssl libssl-dev

若不安裝,之後的步驟將出現錯誤訊息「Ignoring ensurepip failure: pip 7.1.2 requires SSL/TLS」,指出無法安裝pip。若成功的話,則會出現訊息「Successfully installed pip-7.1.2 setuptools-18.2」。

另外,有些Python模組(選用性),相依於底層的模組。若不先安裝,那麼之後步驟將出現類似底下的訊息:
The necessary bits to build these optional modules were not found:
_bz2                  _curses               _curses_panel
_dbm                  _gdbm                 _lzma
_sqlite3              _tkinter              readline

To find the necessary bits, look in setup.py in detect_modules() for the module's name.

若想要這些Python模組與功能的話,請先安裝:
$ sudo apt-get install 模組名

模組名有:libbz2-dev、libncurses5-dev、libncursesw5-dev、libdb-dev、libgdbm-dev、liblzma-dev、libsqlite3-dev 、tk-dev、libreadline-dev、zlib1g-dev、libexpat1-dev。

準備工作完成後,終於要進入主題,首先下載Python 3.5原始碼檔,並且解壓縮:
$ wget https://www.python.org/ftp/python/3.5.0/Python-3.5.0.tgz
$ tar -zxvf Python-3.5.0.tgz

切換目錄,進行組態設定、建置編譯、安裝:
$ cd Python-3.5.0
$ ./configure
$ make
$ sudo make install

注意,其中make步驟費時甚久,Pi約兩小時,Pi 2小於一小時。另外./configure與make install也都需要幾分鐘。

安裝成功後,直譯器檔「python3.5」位於/usr/local/bin裡。

$ python3.5
Python 3.5.0 (default, Sep 27 2015, 20:39:38)
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print('Hello Python 3.5')
Hello Python 3.5
>>> print(*[1], *[2], 3, *[4, 5])
1 2 3 4 5

也已經擁有pip了,以指令pip3.5取用,試著安裝某套件,測試看看吧:

$ sudo pip3.5 install requests
Collecting requests
  Downloading requests-2.7.0-py2.py3-none-any.whl (470kB)
    100% |████████████████████████████████| 471kB 158kB/s
Installing collected packages: requests
Successfully installed requests-2.7.0

耶!

參考資料:

5 comments:

  1. 建議把make install改成make altinstall,才不會覆蓋原本已有的版本。
    Warning

    make install can overwrite or masquerade the python binary. make altinstall is therefore recommended instead of make install since it only installs exec_prefix/bin/pythonversion.

    https://docs.python.org/2/using/unix.html

    ReplyDelete
  2. 葉老師您好, 我在執行 sudo pip3.5 install requests的時候出現如下訊息,
    File "", line 1
    sudo pip3.5 install requests
    ^
    SyntaxError: invalid syntax
    請問如何解決呢? 謝謝您

    ReplyDelete
    Replies
    1. 那一行不是Python程式,
      而是要給Linux系統執行的指令。

      Delete
    2. okok 謝謝老師, 成功了!

      Delete
  3. 冒昧請教老師我在安裝sudo pip3.5 install requests時候出現sudo: pip3.5: command not found,請問老師是否哪裡沒安裝好呢??

    ReplyDelete