ROS cannot find module named torch

I install ROS Noetic, Pytorch v1.12.0, torchvisionon v0.13.0 on NX.
When I use python, import torch, it works. But when I use rosrun to run the same file, it shows No module named torch

Hi @aus, is ROS using python3? Can you check if there is a difference in the Python module search paths between when you run the following command directly, versus with rosrun?

 python3 -c 'import sys; print(sys.path);'
['', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/nvidia/.local/lib/python3.8/site-packages', '/usr/local/lib/python3.8/dist-packages', '/usr/local/lib/python3.8/dist-packages/torchvision-0.12.0a0-py3.8-linux-aarch64.egg', '/usr/lib/python3/dist-packages', '/usr/lib/python3.8/dist-packages']

You may want to try installing the PyTorch wheel globally with pip3 instead of locally: https://bobbyhadz.com/blog/python-pip-install-package-globally

Thank you for your reply.
since I install ubuntu20, I am sure that ros is using python3. I also checked the path by the command “print(sys.path)” directly and versus with rosrun. The result was that the rosrun method contained all the paths which the direct method had, also rosrun method had a few more path so it may not be the reason.

Hmm okay, I’m not sure why it wouldn’t be found then, unless rosrun is running as root/sudo and isn’t finding the PyTorch package installed under your local user. You could try setting the [PYTHONVERBOSE](https://docs.python.org/3/using/cmdline.html#envvar-PYTHONVERBOSE) environment variable or a suggestion like this to trace the imports.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.