本文章讲述ROS系统下如何将python编译为可以执行文件,步骤比较简单,请严格执行避免疏漏
git clone https://gitee.com/alen2020/ros_python_install_mode_files ##取该目录下的cmake目录和setup.py,install.sh到自己节点的目录 cp -r cmake setup.py car_mqtt_api/
如果用到动态参数,还需要拷贝install.sh,并做下列修改(若如需用到动态参数,则以下请忽略)
cp install.sh car_mqtt_api/ ##需要修改install.sh下的package_name,修改为当前包名 package_name= package_path=`rospack find ${package_name}` if [ $# -eq 1 ]; then package_path=$1 fi #注意默认认为.py文件放到src目录下,如果放到scripts下,需要改为scripts #我默认ROS工作空间的前缀目录为/root/ROS/catkin_ws/ ,如不是则请修改 mkdir $package_path/src/$package_name/cfg cp /root/ROS/catkin_ws/devel/lib/python2.7/dist-packages/$package_name/cfg/* $package_path/src/$package_name/cfg
##原结构,.py文件应放在scripts文件夹下 ls
主函数留在当前目录,被调用文件放到子目录,子目录同本包名
1) 修改当前包下的CMakelist
增加如下内容,其中add_subdirectory根据自己python文件存放的目录调整
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/cmake) # include CMake module for Cython include(UseCython) add_custom_target(ReplicatePythonSourceTree ALL ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/ReplicatePythonSourceTree.cmake ${CMAKE_CURRENT_BINARY_DIR} WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) add_subdirectory(src) ##如果用到动态调参,需要另加上下面语句 add_custom_target(install.sh ALL) add_custom_command(TARGET install.sh POST_BUILD COMMAND /bin/sh ${PROJECT_SOURCE_DIR}/install.sh ${PROJECT_SOURCE_DIR}) )
2) 在scripts目录下添加CMakeLists.txt
每一个被引用的文件都要写进去,注意结尾要写主函数的文件名
##添加子目录 add_subdirectory(mypackage) cython_add_standalone_executable(1 MAIN_MODULE 1.py mypackage/2.py 1.py) install(TARGETS 1 RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION})
3) 在scripts目录的子目录下添加CMakeLists.txt
所有被引用的文件都需要添加规则
cython_add_module(2 2.py) set_target_properties(2 PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${CATKIN_DEVEL_PREFIX}/${CATKIN_PACKAGE_PYTHON_DESTINATION}) install(TARGETS 2 LIBRARY DESTINATION ${CATKIN_PACKAGE_PYTHON_DESTINATION}) 省略以下。。。
写两次
cython_add_standalone_executable(car_mqtt_api_main MAIN_MODULE car_mqtt_api_main.py car_mqtt_api_main.py) install(TARGETS car_mqtt_api_main RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION})
改规则后需要加上子目录前缀
原 from mypackage import 2 改后 from mypackage.2 import function
前面说了子目录要与本节点同名,因为编译后并不会以子目录的名称命名,而是以节点名命名,编译生成的可执行文件会放到devel或install的lib/python2.7/dist-packages下,而以源码模式运行则会读取子目录下的cfg文件
如car_mqtt_api编译后动态调参的可执行程序放到如下目录
devel/lib/python2.7/dist-packages/mypackage/cfg
此时需要将该目录下的文件copy到子目录
mkdir -p mypackage/scritps/cfg cp */devel/lib/python2.7/dist-packages/mypackage/cfg scripts/mypackage/cfg
找不到模块:在install/lib/python2.7/dist-packages/car_control
目录下放置__init__.py
文件