VS Code上でPythonを実行する方法|デバッグや単体テストについても解説

- システム
エンジニア - VSCode上でもPythonを実行できるのですか。
- プロジェクト
マネージャー - できますよ。それでは、VSCode上でPythonの実行やデバッグ、単体テスト、カバレッジの取得方法について解説いたしましょう。
VS CodeでPythonの開発をしてみよう
今回は、VS Code上でPythonの開発環境を構築する方法について説明します。
Pythonの実行、デバッグ、単体テスト、カバレッジの取得方法について紹介します。
ここでは、Pythonはインストール済みである前提とします。
興味のある方はぜひご覧ください。
実行
VS Code上でPythonを実行する方法を紹介します。
まず、VS Codeの拡張機能「Python extension for Visual Studio Code」をインストールします。
次に「File」 → 「Open Folder」を選択し、作業フォルダを指定します。
「New File」を選択し、main.pyファイルを作成します。ファイル名は何でも構いません。
以下のように内容を編集します。
1 |
print('Hello World.') |
ソースコード上で右クリックし、「Run Python File in Terminal」を選択します。
VS Code画面下のターミナルに、実行結果が表示されます。
1 2 3 |
PS C:\Python> & C:/Users/user/Anaconda3/python.exe c:/Python/main.py Hello World. PS C:\Python> |
これでVS Codeを使ったPython開発環境が整いました。
デバッグ
VS Code上でPythonをデバッグする方法を紹介します。
VS Codeの画面左にあるデバッグアイコンをクリックし、「create a launch.json file」を選択します。
次に、Debug configurationで「Python File」を選択します。
以下のようなlaunch.jsonが生成されます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Current File", "type": "python", "request": "launch", "program": "${file}", "console": "integratedTerminal" } ] } |
ソースコード上でブレイクポイントを設定します。
デバッグ画面上部にある三角の実行ボタンをクリックするとデバッグができます。
ステップオーバー、ステップイン、ステップアウトなどを駆使して、デバッグしてみてください。
unittest
VS Code上でPythonの単体テストを実行する方法を紹介します。
Ctrl-Shift-P のコマンドパレットから、「Python: Configure Tests」を選択します。
今回は、以下の順に入力・選択します。
1 2 3 |
unittest . test*.py |
以下のようなsettings.jsonが生成されます。
1 2 3 4 5 6 7 8 9 10 11 12 |
{ "python.testing.unittestArgs": [ "-v", "-s", ".", "-p", "test*.py" ], "python.testing.pytestEnabled": false, "python.testing.nosetestsEnabled": false, "python.testing.unittestEnabled": true } |
main.pyを以下のように編集します。
1 2 3 4 5 |
def add(x, y): return x + y def sub(x, y): return x - y def multi(x, y): return x * y |
test.pyを新規作成し、以下のように記述します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import main import unittest class TestCase(unittest.TestCase): def test_1(self): self.assertEqual(main.add(1, 2), 3) def test_2(self): self.assertEqual(main.sub(3, 2), 1) def test_3(self): self.assertEqual(main.multi(2, 3), 6) if __name__ == '__main__': unittest.main() |
VS Code左側のテストアイコンをクリックすると、以下のような階層構造が表示されます。
1 2 3 4 5 |
test.py TestCase test_1 test_2 test_3 |
上部の三角ボタン「Run All Tests」をクリックすると、unittestが実行されます。
カバレッジ
unittestの結果をカバレッジで見る方法を紹介します。まず、coverageをインストールします。
1 |
pip install coverage |
以下のコマンドで、カバレッジを取得します。
1 |
coverage run test.py |
カレントフォルダに「.coverage」ファイルが生成されます。
次に、カバレッジを標準出力するコマンドを実行します。
1 2 3 4 5 6 7 |
$ coverage report Name Stmts Miss Cover ----------------------------- main.py 3 0 100% test.py 11 0 100% ----------------------------- TOTAL 14 0 100% |
カバレッジが表示されることが分かります。
以下のコマンドを実行すると、カバレッジ結果をHTMLで出力します。
1 |
coverage html |
htmlcovフォルダが生成されます。htmlcov配下に以下のようなindex.htmlが生成されます。カバレッジの結果を確認してみてください。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Coverage report</title> <link rel="icon" sizes="32x32" href="favicon_32.png"> <link rel="stylesheet" href="style.css" type="text/css"> <script type="text/javascript" src="jquery.min.js"></script> <script type="text/javascript" src="jquery.ba-throttle-debounce.min.js"></script> <script type="text/javascript" src="jquery.tablesorter.min.js"></script> <script type="text/javascript" src="jquery.hotkeys.js"></script> <script type="text/javascript" src="coverage_html.js"></script> <script type="text/javascript"> jQuery(document).ready(coverage.index_ready); </script> </head> <body class="indexfile"> <div id="header"> <div class="content"> <h1>Coverage report: <span class="pc_cov">100%</span> </h1> <img id="keyboard_icon" src="keybd_closed.png" alt="Show keyboard shortcuts" /> <form id="filter_container"> <input id="filter" type="text" value="" placeholder="filter..." /> </form> </div> </div> <div class="help_panel"> <img id="panel_icon" src="keybd_open.png" alt="Hide keyboard shortcuts" /> <p class="legend">Hot-keys on this page</p> <div> <p class="keyhelp"> <span class="key">n</span> <span class="key">s</span> <span class="key">m</span> <span class="key">x</span> <span class="key">c</span> change column sorting </p> </div> </div> <div id="index"> <table class="index"> <thead> <tr class="tablehead" title="Click to sort"> <th class="name left headerSortDown shortkey_n">Module</th> <th class="shortkey_s">statements</th> <th class="shortkey_m">missing</th> <th class="shortkey_x">excluded</th> <th class="right shortkey_c">coverage</th> </tr> </thead> <tfoot> <tr class="total"> <td class="name left">Total</td> <td>14</td> <td>0</td> <td>0</td> <td class="right" data-ratio="14 14">100%</td> </tr> </tfoot> <tbody> <tr class="file"> <td class="name left"><a href="main_py.html">main.py</a></td> <td>3</td> <td>0</td> <td>0</td> <td class="right" data-ratio="3 3">100%</td> </tr> <tr class="file"> <td class="name left"><a href="test_py.html">test.py</a></td> <td>11</td> <td>0</td> <td>0</td> <td class="right" data-ratio="11 11">100%</td> </tr> </tbody> </table> <p id="no_rows"> No items found using the specified filter. </p> </div> <div id="footer"> <div class="content"> <p> <a class="nav" href="https://coverage.readthedocs.io">coverage.py v5.4</a>, created at 2021-02-11 10:29 +0000 </p> </div> </div> </body> </html> |
- システム
エンジニア - 教えていただいた方法でVS Code上でPythonを使って開発環境を構築してみます。
- プロジェクト
マネージャー - そうですね。ぜひ一度試してみてください。
まとめ
いかがでしたでしょうか。VS Code上でPythonの開発環境を構築する方法について説明しました。
Pythonの実行、デバッグ、単体テスト、カバレッジの取得方法について紹介しました。
ぜひご自身でソースコードを書いて、理解を深めてください。
FEnet.NETナビ・.NETコラムは株式会社オープンアップシステムが運営しています。
株式会社オープンアップシステムはこんな会社です
秋葉原オフィスには株式会社オープンアップシステムをはじめグループのIT企業が集結!
数多くのエンジニアが集まります。

-
スマホアプリから業務系システムまで
スマホアプリから業務系システムまで開発案件多数。システムエンジニア・プログラマーとしての多彩なキャリアパスがあります。
-
充実した研修制度
毎年、IT技術のトレンドや社員の要望に合わせて、カリキュラムを刷新し展開しています。社内講師の丁寧なサポートを受けながら、自分のペースで学ぶことができます。
-
資格取得を応援
スキルアップしたい社員を応援するために資格取得一時金制度を設けています。受験料(実費)と合わせて資格レベルに合わせた最大10万円の一時金も支給しています。
-
東証プライム上場企業グループ
オープンアップシステムは東証プライム上場「株式会社オープンアップグループ」のグループ企業です。
安定した経営基盤とグループ間のスムーズな連携でコロナ禍でも安定した雇用を実現させています。
株式会社オープンアップシステムに興味を持った方へ
株式会社オープンアップシステムでは、開発系エンジニア・プログラマを募集しています。
年収をアップしたい!スキルアップしたい!大手の上流案件にチャレンジしたい!
まずは話だけでも聞いてみたい場合もOK。お気軽にご登録ください。


Python新着案件New Job
マルチロガーソフト開発/東京都豊島区/【WEB面談可/C#経験者/20代後半~40代の方活躍中/経験年数不問】/在宅勤務
月給41万~50万円東京都豊島区(池袋駅)マルチロガーソフト開発/東京都豊島区/【WEB面談可/C#経験者/20代前半の方活躍中/経験1年以上の方活躍中】/在宅勤務
月給29万~34万円東京都豊島区(池袋駅)商品化予定の振動センサーの運用保守/Python/東京都都内/【WEB面談可】
月給50万~60万円東京都都内(-駅)商品化予定の振動センサーの可視化UI開発のテスター/Python/東京都都内/【WEB面談可】
月給25万~35万円東京都都内(-駅)商品化予定の振動センサーの運用保守/Python/東京都都内/【WEB面談可】
月給50万~60万円東京都都内(-駅)商品化予定の振動センサーの可視化UI開発のテスター/Python/東京都都内/【WEB面談可】
月給25万~35万円東京都都内(-駅)