python install模式开发规则

本文章讲述ros系统下如何将python编译为可以执行文件,步骤比较简单,请严格执行避免疏漏

1.下载必须文件

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

2.改造目录结构

##原结构,.py文件应放在scripts文件夹下
ls 

主函数留在当前目录,被调用文件放到子目录,子目录同本包名

3.创建cmakelist规则(有引用关系)

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})
省略以下。。。

4.非引用关系(单文件)

写两次

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})

5. 如何引用包

改规则后需要加上子目录前缀

原
from mypackage import 2
改后
from mypackage.2 import function

6.cfg动态调参

前面说了子目录要与本节点同名,因为编译后并不会以子目录的名称命名,而是以节点名命名,编译生成的可执行文件会放到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

7.常见bug

找不到模块:在install/lib/python2.7/dist-packages/car_control目录下放置__init__.py文件

到此这篇关于ros系统将python包编译为可执行文件的文章就介绍到这了,更多相关python包编译为可执行文件内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!