LoginSignup
7
7

More than 5 years have passed since last update.

Visual Studio Codeの統合ターミナル(コマンドプロンプト)起動時にvenv/conda environmentに入る方法

Last updated at Posted at 2018-01-19

(2018.4.18追記)
ms-python 拡張 2018.1.0 (01 Feb 2018) にて、ターミナル起動の際に自動で仮想環境をactivateする機能が追加されました。
参考: https://github.com/Microsoft/vscode-python/issues/622

その結果、以下の内容は特に必要はなくなりました。

以下、古い記事

何の話

Visual Studio Code上でmspython拡張を使ってpython環境を構築している場合、pythonインタプリタの場所は指定できるが、Ctrl+Shift+@で起動する統合ターミナル上でvenvを使うのは少々面倒。
あらかじめvenvをactivateしたシェルからVSCodeを起動する方法もある1が、VSCode起動時に毎回それを行うのは面倒なので、pythonインタプリタの指定とは別に、統合ターミナル起動時にもvenvを有効にする方法を考えた。こちらの記事2からヒントを得た。

前提

  • Windows + Visual Studio Code環境
  • 統合ターミナルとしてコマンドプロンプトを使用している

他の環境にも応用が利くかもしれない。

方法

cmd.exeの"/k" オプションにactivateをとらせてあげることで、cmd.exe起動時にactivate.batを実行し、そのままターミナルを残してやればよい。
ワークスペースの設定などに次の項目 "terminal.integrated.shellArgs.windows" を追加する。
初回起動時に、バッチファイルの実行確認ダイアログが出るかもしれない。
これで、Ctrl+Shift+@で開いた瞬間から、統合ターミナル内から仮想環境上のcondaやpipコマンドを使ったり、pythonコンソールを起動できたりするようになる。

Python venv環境の場合

activate.batを直接実行する

{
    "terminal.integrated.shellArgs.windows": [
        "/k",
        "<venv root>\\Scripts\\activate.bat"
    ]
}

conda environmentの場合

Anacondaの場合は、実行するactivate.batはAnacondaのディレクトリにあるものでよいが、仮想環境名の指定が必要。
起動がちょっと遅い。

{
    "terminal.integrated.shellArgs.windows": [
        "/k",
        "<Anaconda Root>\\Scripts\\activate.bat <conda env name>",
    ]
}
7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7