ModuleNotFoundError: No module named 'rospkg'

Nagarjun Vinukonda picture Nagarjun Vinukonda · Mar 9, 2021 · Viewed 10.3k times · Source

I am new to ROS,

I have a problem when I import rospy into my script file example.py and run it: It says:

Traceback (most recent call last):
  File "/home/nagarjunv/hk_ws/src/rvo/src/example.py", line 4, in <module>
    import rospy
  File "/opt/ros/melodic/lib/python2.7/dist-packages/rospy/__init__.py", line 49, in <module>
    from .client import spin, myargv, init_node, \
  File "/opt/ros/melodic/lib/python2.7/dist-packages/rospy/client.py", line 52, in <module>
    import roslib
  File "/opt/ros/melodic/lib/python2.7/dist-packages/roslib/__init__.py", line 50, in <module>
    from roslib.launcher import load_manifest  # noqa: F401
  File "/opt/ros/melodic/lib/python2.7/dist-packages/roslib/launcher.py", line 42, in <module>
    import rospkg
ModuleNotFoundError: No module named 'rospkg'

I am importing the following into my script file:The line 4 is rospy

#!/usr/bin/env python3

import sys
import rospy

THis is my CmakeLists:

cmake_minimum_required(VERSION 3.0.2)
project(rvo)

find_package(catkin REQUIRED COMPONENTS
  rospy
  std_msgs
  message_generation
)

 generate_messages(
   DEPENDENCIES
   std_msgs
 )

catkin_package(
#  INCLUDE_DIRS include
#  LIBRARIES rvo
  CATKIN_DEPENDS rospy std_msgs
#  DEPENDS system_lib
)

include_directories(
# include
  ${catkin_INCLUDE_DIRS}
)

This is my package xml:

  <buildtool_depend>catkin</buildtool_depend>
  <build_depend>rospy</build_depend>
  <build_depend>std_msgs</build_depend>
  <build_depend>message_generation</build_depend>
  <build_export_depend>rospy</build_export_depend>
  <build_export_depend>std_msgs</build_export_depend>
  <build_export_depend>message_generation</build_export_depend>
  <exec_depend>rospy</exec_depend>
  <exec_depend>std_msgs</exec_depend>
  <exec_depend>message_runtime</exec_depend>

I specify both in CMakelists and Package XML 'rospy' and importing it. I also checked my ros has rospy package available. BUt, I dont understand why I am having trouble running my script file?

rosrun rvo example.py 

I will be glad to provide more details about this error. Can any please let me know the solution to this problem?

Answer

Markus Weber picture Markus Weber · Feb 1, 2022

Try to change the shebang (line 1) according to the python version your ROS distro works with.

For melodic or earlier: #!/usr/bin/env python2

For noetic or later: #!/usr/bin/env python3