ROS2调用interface proto时自定义消息报ModuleNotFoundError求助
解决ROS2自定义消息
ros2 interface proto报错ModuleNotFoundError的问题 问题背景
在Windows系统下的ROS2 Humble/Galactic/Rolling版本中,自定义消息包custom的消息CustomMessage可通过ros2 interface list被检索到,ros2 interface show也能正常输出消息结构,但执行ros2 interface proto custom/msg/CustomMessage时触发ModuleNotFoundError: No module named 'custom'错误。自定义消息定义如下:
string custom_string trajectory_msgs/JointTrajectory custom_trajectory
解决方案
1. 确认自定义包的构建与环境生效
- 确保在Colcon工作空间中完成正确构建:执行
colcon build --packages-select custom,检查构建日志无编译错误。 - 构建完成后必须source工作空间的setup文件:
- PowerShell:
. install/setup.ps1 - Command Prompt:
install\setup.bat
- PowerShell:
- 验证生成的Python模块:检查工作空间下
install/custom/lib/python3.8/site-packages路径是否存在custom目录,该目录需包含msg子目录及自动生成的消息Python文件(如_custommessage.py)。
2. 检查PYTHONPATH环境变量
- 执行命令查看PYTHONPATH:
- PowerShell:
echo $env:PYTHONPATH - Command Prompt:
echo %PYTHONPATH%
- PowerShell:
- 确认输出中包含自定义包的Python路径(即
install/custom/lib/python3.8/site-packages),若未包含则手动添加:- PowerShell:
$env:PYTHONPATH += ";$PWD/install/custom/lib/python3.8/site-packages" - Command Prompt:
set PYTHONPATH=%PYTHONPATH%;%cd%\install\custom\lib\python3.8\site-packages
- PowerShell:
3. 验证CMakeLists.txt与package.xml配置
CMakeLists.txt需包含以下关键配置:
find_package(ament_cmake REQUIRED) find_package(rosidl_default_generators REQUIRED) find_package(trajectory_msgs REQUIRED) rosidl_generate_interfaces(${PROJECT_NAME} "msg/CustomMessage.msg" DEPENDENCIES trajectory_msgs ) ament_export_dependencies(rosidl_default_runtime) ament_package()
package.xml需包含必要依赖:
<buildtool_depend>ament_cmake</buildtool_depend> <build_depend>rosidl_default_generators</build_depend> <build_depend>trajectory_msgs</build_depend> <exec_depend>rosidl_default_runtime</exec_depend> <exec_depend>trajectory_msgs</exec_depend> <member_of_group>rosidl_interface_packages</member_of_group>
4. 清理后重新构建
删除工作空间的build、install、log目录,重新执行:
colcon build --packages-select custom
完成后再次source setup文件,然后运行ros2 interface proto custom/msg/CustomMessage测试。
内容的提问来源于stack exchange,提问作者Spyros K
相关产品推荐
相关产品推荐

