「No module named ‘websocket’」が発生
事態はラズベリーパイにておきました。
pythonコードを実行しようとしたら以下のエラー。
No module named 'websocket'「websocketのmoduleが必要なのか」と思い、pipでinstallしようとすると以下のエラー
$ pip install websocket
error: externally-managed-environment
× This environment is externally managed
╰─> To install Python packages system-wide, try apt install
python3-xyz, where xyz is the package you are trying to
install.
If you wish to install a non-Debian-packaged Python package,
create a virtual environment using python3 -m venv path/to/venv.
Then use path/to/venv/bin/python and path/to/venv/bin/pip. Make
sure you have python3-full installed.
For more information visit http://rptl.io/venv
note: If you believe this is a mistake, please contact your Python installation or OS distribution provider. You can override this, at the risk of breaking your Python installation or OS, by passing --break-system-packages.
hint: See PEP 668 for the detailed specification.
「error: externally-managed-environment」が発生
$ pip install --break-system-packages websocketと「–break-system-packages」を付けて実行してもできるらしいけど、リスクがあるらしいです。
The installer should have a way for the user to override these rules, such as a command-line flag –break-system-packages. This option should not be enabled by default and should carry some connotation that its use is risky.
https://peps.python.org/pep-0668/
上書きされちゃうかもしれないって書いてあります。
ということで、仮想環境を用意する方法で対応します。
$ python -m venv test仮想環境の名前は今回はtestにしています。
以降、testのところは個々人で設定した仮想環境名に置き換えてください。
では、websocketをインストールします。
$ test/bin/pip install websocketしかしここで新たなエラーが発生しました。
「ImportError: cannot import name ‘WebSocketApp’ from ‘websocket’ (/home/xxxx/.local/lib/python3.11/site-packages/websocket/init.py)」発生
再度、pythonコードを実行しようとすると、
ImportError: cannot import name 'WebSocketApp' from 'websocket' (/home/xxxx/.local/lib/python3.11/site-packages/websocket/init.py)
が発生しました。
これはこちらのページが参考になりました。
websocketではなくて、websocket-clientと言うことなので、websocketをアンインストールして、websocket-clientをインストールします。
$ test/bin/pip uninstall websocket
$ test/bin/pip install websocket-clientこれで解消されるかと思います。
ちなみに、実際にpythonコードを実行するときは以下のような形で実行します。
$ test/bin/python test.py

