ros2 build_error ai_generated true

ImportError: No module named 'my_package' when running colcon build --packages-select my_package

ID: ros2/colcon-build-python-import-error-no-module-named-package

Also available as: JSON · Markdown · 中文
85%Fix Rate
84%Confidence
1Evidence
2023-03-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
ROS2 Humble active
ROS2 Iron active
colcon-core 0.13.x active
colcon-ros 0.5.x active

Root Cause

The Python package in the ROS2 workspace is missing a __init__.py file or has an incorrect package structure, causing colcon to fail to import it during build.

generic

中文

ROS2 工作空间中的 Python 包缺少 __init__.py 文件或包结构不正确,导致 colcon 在构建期间无法导入它。

Official Documentation

https://docs.ros.org/en/humble/Tutorials/Beginner-Client-Libraries/Creating-Your-First-ROS2-Package.html

Workarounds

  1. 95% success Create an empty __init__.py file in the package's source directory: 'touch src/my_package/my_package/__init__.py'
    Create an empty __init__.py file in the package's source directory: 'touch src/my_package/my_package/__init__.py'
  2. 90% success Verify the package structure: the source directory should contain a subdirectory with the same name as the package, containing __init__.py and other modules.
    Verify the package structure: the source directory should contain a subdirectory with the same name as the package, containing __init__.py and other modules.

中文步骤

  1. 在包的源目录中创建一个空的 __init__.py 文件:'touch src/my_package/my_package/__init__.py'
  2. 验证包结构:源目录应包含一个与包同名的子目录,其中包含 __init__.py 和其他模块。

Dead Ends

Common approaches that don't work:

  1. 60% fail

    The import error is specific to the package; building all packages may mask the issue or fail elsewhere.

  2. 90% fail

    The error is due to missing __init__.py, not build artifacts; deleting build won't fix it.

  3. 70% fail

    While this may install the package, it bypasses colcon's build system and may cause inconsistencies in the workspace.