Skip to content

Instantly share code, notes, and snippets.

@chairco
Last active July 2, 2020 06:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chairco/3b65be85a045ef47ca4cfb0c77b5b912 to your computer and use it in GitHub Desktop.
Save chairco/3b65be85a045ef47ca4cfb0c77b5b912 to your computer and use it in GitHub Desktop.
how to fix windows vscode python bash terminal environment can't use previous command

如何修復 windows 上 vscode 使用 bash shell 無法用方向鍵切換歷史指令

最近在 windows 10 系統改用 vscode 來寫 Python,優點不少,像是有很多套件可以安裝(vim, git, jupyter etc)、環境很彈性例如可以設定只要選定設定好的虛擬環境,就自動將 terminal 上的 bash shell 啟用成對應的虛擬環境 REPL 介面。

不過還是遇到一些問題,就是進入互動介面時候沒辦法使用方向鍵上與下 (arrow up, down) 來快速切換上一個歷史指令 (previouw command) 但在 windows 自己的 shell 例如 powershell 就不會有這問題。

Google 後確定應該不是 vscode 問題,想想也合理,因為它也只是掛上某個 shell,至於掛到哪個 shell? 前面有提到我的環境似乎是跑在一個 bash shell 上,為了確認:

  1. 首先在 vscode 裡用快速鍵 ctrl + shift + p
  2. 叫出 pereference 設定,
  3. 接著打上 select default shell 如下

#

就能看到如下安裝在 windows 上面的 shell (圖片來自; 我自己環境是多一個 WSL bash shell)

#

在我 vscode 上選擇使用的 bash 不是 powershell 而是安裝 git 時候也同時安裝的 git bash shell (其實忘記是不是自己選的還是 vscode 預設)

再來去搜尋一下關於 git bash shell 為什麼沒有辦法使用方向鍵來切換 history command(previous command),過去在 os x 環境也有遇過這類問題,原因是實現這類紀錄 history 都是透過一個 GNU readline 的函式庫完成。 Python 內則也有 readline 的函式庫做介面,一般來說出現問題 1 是重新安裝 readline interface 2 是重新 build Python

不過在 windows 沒有readline GNU 這個東西 至於怎模實作則還沒認真去細讀,不過 git bash 到是能夠透過 pyreadline 來達到,可以參考 stack overflow 和舊版 2.7 docs 上說明來做,我的作法整理如下:

  1. 先在系統的 Python 上 pip install pyreadline
  2. 接著在家目錄建立一個 .py 檔案, 就叫 .pythonstartup.py 內容:
# -*- coding: utf-8 -*-

# python startup file
# import readline
from pyreadline import Readline # <-- win 上的 readline package

import rlcompleter
import atexit
import os

readline = Readline() # <-- 這行取代官方 docs 上的 import readline

# tab completion
readline.parse_and_bind('tab: complete')
# history file
histfile = os.path.join(os.environ['HOME'], '.pythonhistory')
try:
    readline.read_history_file(histfile)
except IOError:
    pass

atexit.register(readline.write_history_file, histfile) 
del os, histfile, readline, rlcompleter
  1. windows 修改系統變數: 控制台 -> 系統 -> 進階系統設定 -> 環境變數 裡面建立一個使用者的環境變數 PythonStartFile 指到前面建立的 .pythonstartup.py

  2. 接著重新開啟 vscode shell 就完成了

Imgur

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment