Abbas
Abbas

Reputation: 137

Issue to import python libraries/moduls for a ROS2 subscriber

I am new to use ROS in my project. I have installed ROS2 humble on Ubuntu 22.04. I need to import different python codes/functions as modules to a ROS2 subscriber (python code).

They are:

  1. common_utils.py in utils folder
  2. build_network which is a function in pointpillar.py.

Both python codes are located in another folder which is not a ROS2 package (home/user/Machine_Learning) and its directory is different from subscriber directory (home/user/DL_ws/src/object_detection/object_detection/pc_subscriber.py).

In my subscriber code, I changed the directory to Machine_Learning folder, then I used from utils import common_utils and from pointpillar import build_network.

With/without updating package.xml (adding utils and pointpillar for </exec_depend>), then colcon build, when I use ros2 run object_detection listener, I get this error: ModuleNotFoundError: No module named 'utils' or ModuleNotFoundError: No module named 'pointpillar'.

How can I solve this issue?

I appreciate any help in advance.

Thanks, Abbas

Upvotes: 0

Views: 268

Answers (1)

asymptote
asymptote

Reputation: 1402

You can append path of the python code/modules to system paths:

import sys

extra_path = '/home/user/Machine_Learning' # path to folder with python code to import
sys.path.append(extra_path)

from utils import common_utils
from pointpillar import build_network

extra_path can be either absolute or relative path to the code directory.

Upvotes: 0

Related Questions