【学习笔记】使用python启动launch文件

项目场景:

由于在采用人脸识别时,cv.VideoCapture会占用摄像头设备,导致后续启动摄像头程序失败,所以想到当人脸识别结束后,释放占用后,在python文件中启动launch文件,避免出现占用拥挤的问题


解决方案:

感谢:使用Python代码启动launch文件_wongHome的博客-CSDN博客_launch python

import roslaunch
import time

uuid = roslaunch.rlutil.get_or_generate_uuid(None, False)
roslaunch.configure_logging(uuid)
tracking_launch = roslaunch.parent.ROSLaunchParent(
    uuid, ["/home/spark/spark_noetic/src/3rd_app/move2grasp/launch/ar_grasp_ready.launch"])
tracking_launch.start()
while not rospy.is_shutdown():
    time.sleep(1)

上述为启动的代码,将需要启动的launch文件路径更换成自己的即可


代码解读

如有解读错误,请多多指教

roswiki中链接(roslaunch/API Usage - ROS Wiki

roslaunch的源代码(GitHub - ros/ros_comm: ROS communications-related packages, including core client libraries (roscpp, rospy, roslisp) and graph introspection tools (rostopic, rosnode, rosservice, rosparam).

1.uuid = roslaunch.rlutil.get_or_generate_uuid(None, False)

def get_or_generate_uuid(options_runid, options_wait_for_master)
options_runid: run_id value from command-line or None, str
options_wait_for_master: the wait_for_master command option. If this is True, it means that we must retrieve the value from the parameter server and need to avoid any race conditions with the roscore being initialized. bool
Full name: roslaunch.rlutil.get_or_generate_uuid

从函数名可以知道,这是一个获取或者生成run_id号的函数,提供两个参数选择,分别是run_id和是否等待master。选择none以父进程创建id号,以及不等待参数服务器反应

完整声明贴在这里:

def get_or_generate_uuid(options_runid, options_wait_for_master):
    """
    :param options_runid: run_id value from command-line or ``None``, ``str``
    :param options_wait_for_master: the wait_for_master command
      option. If this is True, it means that we must retrieve the
      value from the parameter server and need to avoid any race
      conditions with the roscore being initialized. ``bool``
    """

    # Three possible sources of the run_id:
    #
    #  - if we're a child process, we get it from options_runid
    #  - if there's already a roscore running, read from the param server
    #  - generate one if we're running the roscore
    if options_runid:
        return options_runid

    # #773: Generate a run_id to use if we launch a master
    # process.  If a master is already running, we'll get the
    # run_id from it instead
    param_server = rosgraph.Master('/roslaunch')
    val = None
    while val is None:
        try:
            val = param_server.getParam('/run_id')
        except:
            if not options_wait_for_master:
                val = roslaunch.core.generate_run_id()
    return val

2.roslaunch.configure_logging(uuid)

使用roslaunch的脚本必须调用configure_logging,将刚刚生成的uuid传递进去

完整声明贴在这里:

def configure_logging(uuid):
    """
    scripts using roslaunch MUST call configure_logging
    """
    try:
        import socket
        import rosgraph.roslogging
        logfile_basename = os.path.join(uuid, '%s-%s-%s.log'%(NAME, socket.gethostname(), os.getpid()))
        # additional: names of python packages we depend on that may also be logging
        logfile_name = rosgraph.roslogging.configure_logging(NAME, filename=logfile_basename)
        if logfile_name:
            print("... logging to %s"%logfile_name)

        # add logger to internal roslaunch logging infrastructure
        logger = logging.getLogger('roslaunch')
        roslaunch_core.add_printlog_handler(logger.info)
        roslaunch_core.add_printerrlog_handler(logger.error)
    except:
        print("WARNING: unable to configure logging. No log files will be generated", file=sys.stderr)

3.tracking_launch = roslaunch.parent.ROSLaunchParent()

class ROSLaunchParent(object):
    """
    ROSLaunchParent represents the main 'parent' roslaunch process. It
    is responsible for loading the launch files, assigning machines,
    and then starting up any remote processes. The __main__ method
    delegates most of runtime to ROSLaunchParent.

    This must be called from the Python Main thread due to signal registration.    
    """

简单理解为,roslaunch的父级进程,用以加载启动文件,分配机器,然后启动任何远程进程。

 def __init__(self, run_id, roslaunch_files, is_core=False, port=None, local_only=False, process_listeners=None,
            verbose=False, force_screen=False, force_log=False, is_rostest=False, roslaunch_strs=None, num_workers=NUM_WORKERS, timeout=None, master_logger_level=False, show_summary=True, force_required=False,
            sigint_timeout=DEFAULT_TIMEOUT_SIGINT, sigterm_timeout=DEFAULT_TIMEOUT_SIGTERM):
        """
        @param run_id: UUID of roslaunch session
        @type  run_id: str
        @param roslaunch_files: list of launch configuration
            files to load
        @type  roslaunch_files: [str]

参数主要为,run_id,roslaunch文件

4.tracking_launch.start()

启动launch文件

def start(auto_terminate=True)
Run the parent roslaunch.

@param auto_terminate: stop process monitor once there are no
more processes to monitor (default True). This defaults to
True, which is the command-line behavior of roslaunch. Scripts
may wish to set this to False if they wish to keep the
roslauch infrastructure up regardless of processes being
monitored.
Full name: roslaunch.parent.ROSLaunchParent.start

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
TX2指的是NVIDIA公司推出的Jetson TX2开发板,是一款高性能嵌入式平台。在TX2上,可以使用ROS(Robot Operating System)开发机器人应用程序。 在TX2上不登录的情况下,要实现开机自动启动launch文件,可以通过以下几个步骤操作: 1. 编写launch文件:首先,需要编写一个包含所需节点和参数的launch文件launch文件可以定义要启动的节点、节点之间的连接关系、运行参数等等。 2. 设置启动脚本:创建一个启动脚本(Shell脚本),可以将其命名为"startup.sh"。在启动脚本中,需要调用roslaunch命令来启动刚才编写的launch文件。 3. 修改系统配置文件:修改Linux系统的配置文件,以便将启动脚本添加到系统启动时自动执行的程序列表中。 具体操作步骤如下: 1. 在TX2上创建一个新的包,可以使用以下命令: ```shell $ cd ~/catkin_ws/src $ catkin_create_pkg my_package rospy ``` 2. 在包中创建一个launch文件,例如"my_launch.launch"。在launch文件中,编写要启动的节点和参数设置,示例如下: ```xml <launch> <node name="my_node" pkg="my_package" type="my_node.py" output="screen"> <param name="my_param" value="123" /> </node> </launch> ``` 3. 创建一个启动脚本"startup.sh",示例如下: ```shell #!/bin/bash source /opt/ros/melodic/setup.bash source ~/catkin_ws/devel/setup.bash export ROS_MASTER_URI=http://localhost:11311 export ROS_IP=your_ip_address roslaunch my_package my_launch.launch ``` 4. 将启动脚本复制到/etc/init.d/目录下,并添加执行权限,示例如下: ```shell $ sudo cp ~/catkin_ws/src/my_package/startup.sh /etc/init.d/ $ sudo chmod +x /etc/init.d/startup.sh ``` 5. 修改rc.local文件,添加启动脚本的执行,示例如下: ```shell $ sudo nano /etc/rc.local ``` 在文件末尾添加以下一行: ```shell /etc/init.d/startup.sh ``` 按Ctrl + X保存并退出。 6. 重启TX2,即可自动执行启动脚本,实现开机启动launch文件。 以上就是在TX2上不登录的情况下,实现开机自动启动launch文件的方法。注意,在修改系统配置文件时要小心操作,避免误操作导致系统不稳定。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值