2.2.1 ROS2 在功能包中编写 Python 节点

2.2.1 在功能包中编写 Python 节点

创建一个 ROS 2 的功能包,可以先使用 ros2 pkg create --help 来查看参数

bash 复制代码
$ ros2 pkg create --help
usage: ros2 pkg create [-h] [--package-format {2,3}] [--description DESCRIPTION] [--license LICENSE] [--destination-directory DESTINATION_DIRECTORY]
                       [--build-type {cmake,ament_cmake,ament_python}] [--dependencies DEPENDENCIES [DEPENDENCIES ...]] [--maintainer-email MAINTAINER_EMAIL]
                       [--maintainer-name MAINTAINER_NAME] [--node-name NODE_NAME] [--library-name LIBRARY_NAME]
                       package_name

Create a new ROS 2 package

positional arguments:
  package_name          The package name

options:
  -h, --help            show this help message and exit
  --package-format {2,3}, --package_format {2,3}
                        The package.xml format.
  --description DESCRIPTION
                        The description given in the package.xml
  --license LICENSE     The license attached to this package; this can be an arbitrary string, but a LICENSE file will only be generated if it is one of the
                        supported licenses (pass '?' to get a list)
  --destination-directory DESTINATION_DIRECTORY
                        Directory where to create the package directory
  --build-type {cmake,ament_cmake,ament_python}
                        The build type to process the package with
  --dependencies DEPENDENCIES [DEPENDENCIES ...]
                        list of dependencies
  --maintainer-email MAINTAINER_EMAIL
                        email address of the maintainer of this package
  --maintainer-name MAINTAINER_NAME
                        name of the maintainer of this package
  --node-name NODE_NAME
                        name of the empty executable
  --library-name LIBRARY_NAME
                        name of the empty library

创建 python 功能包:

bash 复制代码
$ ros2 pkg create demo_python_pkg --build-type ament_python --license Apache-2.0
going to create a new package
package name: demo_python_pkg
destination directory: /home/hw/Development/shx-notebooks/ros_study/chapt02
package format: 3
version: 0.0.0
description: TODO: Package description
maintainer: ['hw <2979532572@qq.com>']
licenses: ['Apache-2.0']
build type: ament_python
dependencies: []
creating folder ./demo_python_pkg
creating ./demo_python_pkg/package.xml
creating source folder
creating folder ./demo_python_pkg/demo_python_pkg
creating ./demo_python_pkg/setup.py
creating ./demo_python_pkg/setup.cfg
creating folder ./demo_python_pkg/resource
creating ./demo_python_pkg/resource/demo_python_pkg
creating ./demo_python_pkg/demo_python_pkg/__init__.py
creating folder ./demo_python_pkg/test
creating ./demo_python_pkg/test/test_copyright.py
creating ./demo_python_pkg/test/test_flake8.py
creating ./demo_python_pkg/test/test_pep257.py

接下来可以在 demo_python_pkg/demo_python_pkg/ 下创建 python_node.py

python 复制代码
import rclpy
from rlcpy.node import Node


def main():
    rclpy.init()
    node = Node('python_node')
    node.get_logger().info('你好 Python 节点')
    rclpy.spin(node)
    rclpy.shutdown()

这里的代码其实和之前的 Python 文件时一样的,只是没有 if __name__ = '__main__',因为 ROS 2 的功能包会自动生成可执行文件去帮我们调用这个代码,因此我们还需要在功能包中去声明可执行文件的名字是什么和对应的 main 函数。

在 setup.py 的 console_scripts 添加

  • 第一个 python_node:可执行文件的名字
    • 可以取任何名字,不一定要与代码文件的名字保持一致
  • demo_python_pkg:包的名字
  • python_node:代码文件的名字
  • main:函数的名字

写完这个之后,一般还要再清单文件 package.xml 中加一个依赖声明。因为我们在代码中使用了 rclpy 库,所以添加依赖信息 <depend>rclpy</depend>

接下来就可以构建功能包,使用命令 colcon build 进行构建,会构建当前及子目录下的所有功能包,并在同级目录产生 build,install,log 三个文件夹。

bash 复制代码
hw@LAPTOP-OF07PRPE:~/Development/shx-notebooks/ros_study/chapt2$ colcon build
Starting >>> demo_python_pkg
Finished <<< demo_python_pkg [0.47s]          

Summary: 1 package finished [0.76s]

构建完成后,我们可以发现多出了 build install log 这三个文件夹。

复制代码
.
├── build  放置构建过程中的中间文件
├── demo_python_pkg
├── install  放置构建结果                                                                                                              
│   ├── COLCON_IGNORE
│   ├── _local_setup_util_ps1.py
│   ├── _local_setup_util_sh.py
│   ├── demo_python_pkg  来自 demo_python_pkg
│   │   ├── lib
│   │   │   ├── demo_python_pkg
│   │   │   │   └── python_node  之前在 setup.py 中指定生成的可执行文件
│   │   │   └── python3.10
│   │   │       └── site-packages
│   │   │           ├── demo_python_pkg  把外面的包拷贝到这里,python_node 可执行文件也会到这里来找 main 函数
│   │   │           │   ├── __init__.py
│   │   │           │   ├── __pycache__
│   │   │           │   │   ├── __init__.cpython-310.pyc
│   │   │           │   │   └── python_node.cpython-310.pyc
│   │   │           │   └── python_node.py
│   │   │           └── demo_python_pkg-0.0.0-py3.10.egg-info
│   │   └── share
│   ├── local_setup.bash
│   ├── local_setup.ps1
│   ├── local_setup.sh
│   ├── local_setup.zsh
│   ├── setup.bash
│   ├── setup.ps1
│   ├── setup.sh
│   └── setup.zsh
└── log

如果直接运行命令 ros2 run demo_python_pkg python_node 就会提示找不到功能包

python 复制代码
$ ros2 run demo_python_pkg python_node
Package 'demo_python_pkg' not found

这是因为 ros2 run 会通过 AMENT_PREFIX_PATH 环境变量来查找功能包,该值默认的是 ROS 2 的安装目录,而 demo_python_pkg 包的安装目录在 install 目录下,因此我们需要修改 AMENT_PREFIX_PATH 。可以直接使用 install 目录下的 setup.bash 脚本来修改环境变量。

bash 复制代码
$ echo $AMENT_PREFIX_PATH
/opt/ros/humble
$ source install/setup.bash 
$ echo $AMENT_PREFIX_PATH
/home/hw/Development/shx-notebooks/ros_study/chapt2/install/demo_python_pkg:/opt/ros/humble
$ ros2 run demo_python_pkg python_node
[INFO] [1764734395.496624161] [python_node]: 你好 Python 节点
相关推荐
默_笙3 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
小羊没烦恼!3 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
qq_426003963 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫3 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技3 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读3 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时3 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
C语言小火车3 天前
C/C++ 为什么需要编译器?
开发语言·c++
奇思妙想聪明勤奋的小羊3 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1233 天前
2026年第38周GitHub趋势周报
python·科技·github