Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Import python script to different ROS2 package

I have created a package called custom_msg which has the following structure:

src
    custom_msg
        msg
            CustomMsg.msg
        constants
            msg_constants.py
        CMakeLists.txt
        package.xml

Where CMakeLists.txt:

cmake_minimum_required(VERSION 3.5)

project(custom_msg)

# Default to C++14
if(NOT CMAKE_CXX_STANDARD)
  set(CMAKE_CXX_STANDARD 14)
endif()

if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
  add_compile_options(-Wall -Wextra -Wpedantic)
endif()

find_package(ament_cmake REQUIRED)
find_package(builtin_interfaces REQUIRED)
find_package(rosidl_default_generators REQUIRED)

rosidl_generate_interfaces(custom_msg
  "msg/CustomMsg.msg"
  DEPENDENCIES builtin_interfaces
)

ament_package()

package.xml:

<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
  <name>custom_msg</name>
  <version>0.7.6</version>
  <description>Custom messages for real-time communication between nodes of the truck.</description>

  <maintainer email="hector.esteban@man.de">Hector Esteban</maintainer>

  <license>Apache License 2.0</license>

  <author>Hector Esteban</author>

  <buildtool_depend>ament_cmake</buildtool_depend>
  <buildtool_depend>rosidl_default_generators</buildtool_depend>

  <depend>rosidl_default_generators</depend>
  <depend>common_interfaces</depend>

  <exec_depend>rosidl_default_runtime</exec_depend>

  <test_depend>ament_lint_auto</test_depend>
  <test_depend>ament_lint_common</test_depend>

  <member_of_group>rosidl_interface_packages</member_of_group>

  <export>
    <build_type>ament_cmake</build_type>
  </export>
</package>

And msg_constants.py:

#! /usr/bin/env python
OK = 0
OBJECTIVE_NOT_REACHED = 1
PLANNING_EMPTY = 2

After doing:

colcon build --symlink-install
source install/local_setup.bash

When I import from another package msg_constants.py:

from custom_msg.constants import msg_constants as msg_type
from custom_msg.msg import CustomMsg

I can import CustomMsg but not msg_constants

[planning_prob_node-2]     from custom_msg.constants import msg_constants as msg_type
[planning_prob_node-2] ModuleNotFoundError: No module named 'custom_msg.constants'