How to import a class from another package

Hi all, I have written a class called move_drone_class under the filename move_drone.py in a separate package called square_drone.

Now I want to access it from a new file called script.py created inside another package testpkg

script.py is as below:

#! /usr/bin/env python
import rospy
from move_drone import move_drone_class


if __name__ == '__main__':
    rospy.init_node("AccessClassFromNewPackage")
    move_drone_obj=move_drone_class()
    move_drone_obj.takeoff()
    move_drone_obj.move_around_in_random()
    rospy.sleep(3)
    move_drone_obj.land()

1.When i try to access it, I get the following error, Can you help solve this? The chapter “using python classes” in ROS 5 days basics, talks about this, but there the file imported was from the same package.
2.Is it a convention to copy the file we want to import, into the current package we are working on? because this method worked for me

Traceback (most recent call last):
  File "/home/user/catkin_ws/src/testpkg/src/script.py", line 3, in <module>
    from move_drone import move_drone_class
ModuleNotFoundError: No module named 'move_drone'

To use the source code of packageA in packageB, you need to do this when creating packageB:

catkin_create_pkg packageB [other_dependencies] packageA

Thank you, the method worked

1 Like

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