LoginSignup
10
15

More than 3 years have passed since last update.

Visual Studio Code を使ったPython環境の構築

Last updated at Posted at 2018-12-20

はじめに

当ドキュメントでは、Visual Studio Code を使った Python開発環境の構築方法についてまとめる。以下を導入することにより、Pythonの開発をし易くする。

  • Visual Studio Code
  • Python拡張
  • flake8

環境前提

  • エディタは、Visual Studio Codeを使う
  • venv による 仮想環境を使う
  • 静的解析は flake8 を利用する

Visual Studio Code 導入・Python用の設定手順

Visual Studio Code インストール

インストール後、以下の拡張機能をインストールする。
(リンクからでも可能だが、Visual Studio Code の拡張機能からも検索、インストール可能)

プロキシ設定(会社での利用などで必要な場合)

  1. Visual Studio Code を起動し、 ファイル→基本設定→設定→ユーザ設定タブ
  2. アプリケーション→プロキシのproxyに以下を設定(認証が必要な場合、user:password@が必要)

http:user:password@proxyのURL:port

日本語化

Python拡張

ワークスペース(作業ディレクトリ)の作成

  1. 適当な場所にディレクトリを作り、そこをワークスペースとする。(ここでは、 (work_space_dir) とする。)
  2. Visual Studio Code で、そのディレクトリを開く。

仮想環境の設定

  1. ターミナル→新しいターミナル(またはCtrl+Shift+@)で、ターミナルを開く。
  2. ワークスペースのルートディレクトリ (work_space_dir) で、 python -m venv venv を実行
  3. venv ディレクトリが出来たら、 venv\Scripts\activate を実行
  4. (venv) C:\(work_space_dir)> というようにターミナルの表示が変わる
  5. pip install flake8 で flake8 をインストールする
  6. pip install black で black をインストールする

Visual Studio Code で静的解析, formatter を有効にする

設定

  1. ファイル→基本設定→設定→ワークスペースの設定タブ
  2. 「settings.json で編集」リンクをクリックして、以下のコードをコピペする
{
    "python.linting.flake8Enabled": true,
    "python.pythonPath": "(work_space_dir)\\venv\\Scripts\\python.exe",
    "python.linting.pylintEnabled": false,
    "python.linting.lintOnSave": true,
    "python.formatting.provider": "black",
    "editor.formatOnSave": true,
    "editor.formatOnPaste": false
}

設定確認

以下の様に適当なPythonファイルを作成して、from の所に赤い波線が出たらOK。
波線にカーソルを合わせると、 'datetime.datetime' imported but unusedflake8(F401) と表示されるはず。

test.py

# coding: utf-8
from datetime import datetime

参考

https://code.visualstudio.com/docs/python/environments
https://qiita.com/shinno21/items/de09a2533097cbfd5f66

10
15
2

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
10
15