0
0

More than 1 year has passed since last update.

VSCodeでpip installしたパッケージが参照出来ない時の解決方法

Last updated at Posted at 2023-01-26

VSCode上でpip installしたパッケージが参照出来なかった…

ふとしたきっかけでdiscordのbotを作る事になったので、
bot開発環境のためpythonの導入を進めてみた所、掲題の部分でハマったお話。。。

その際、Pip ManagerというVSCode上でpipでインストールしたパッケージの
参照・管理まで解決してくれる拡張機能を見つけたので事例も兼ねて紹介します。

※discordのbot開発の手引きはこちらを参考にしました
https://www.freecodecamp.org/japanese/news/create-a-discord-bot-with-python/

記憶を頼りにpythonのインストールと環境設定

  • Python.orgから取り合えず最新版をDL
      → インストーラに言われるまま設定

  • VSCodeの拡張機能のPythonをインストール

  • Python拡張機能の導入手順を見ながらpy.exeにPathを通す
    → <ユーザディレクトリ>\AppData\Local\Programs\Python\Python311

とりあえずHelloWorld

※venvでCreateした

print("Hello World!")

→ 成功

pipでdiscord.pyをインストール

# discord.pyをpipでインストール
> py -3 -m pip install -U discord.py
~エラー無し~

# パッケージ追加の確認
> py -3 -m pip list
Package            Version
------------------ -------
aiohttp            3.8.3
aiosignal          1.3.1
async-timeout      4.0.2
attrs              22.2.0
charset-normalizer 2.1.1
discord.py         2.1.0
frozenlist         1.3.3
idna               3.4
multidict          6.0.4
pip                22.3.1
setuptools         65.5.0
yarl               1.8.2

OKっぽい

botのサンプルコードをVSCodeから実行してみる ※コード引用元

import discord
import os

client = discord.Client()

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('$hello'):
        await message.channel.send('Hello!')

client.run(os.getenv('TOKEN'))

すると。。。

(.venv) PS C:\Users\XXXXX\project\XXXXX> & c:/Users/XXXXX/project/XXXXX/.venv/Scripts/python.exe c:/Users/XXXXX/project/XXXXX/main.py
Traceback (most recent call last):
  File "c:\Users\XXXXX\project\XXXXX\main.py", line 1, in <module>
    import discord
ModuleNotFoundError: No module named 'discord'

discordのモジュールが見つからないよ、と
解決方法を探す旅が始まる・・・

解決編

VSCode拡張機能で良い感じにpipの管理してくれる物が見つかった

前章でpip installしたパッケージの参照を解決する方法を見つける前に、
VSCode上でpipの管理も完結できる拡張機能が見つかったのでそちらを導入

・Pip Manager
https://marketplace.visualstudio.com/items?itemName=slightc.pip-manager

  • Pip ManagerのSearch packageでdiscord.pyをインストール
    ※左:discord.pyインストール前 右:インストール後
    image.png

・今度はdiscord.py参照出来てそう!
image.png

  • 実行 → 無事に動作しました!

結論

Pip ManagerはVSCode上でpipインストールしたパッケージの参照・管理を完結出来るので便利そうでした!

0
0
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
0
0