【学习笔记】使用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的父级进程,用以加载启动文件,分配机器,然后启动任何远程进程。

扫描二维码关注公众号,回复: 16774146 查看本文章
 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

猜你喜欢

转载自blog.csdn.net/weixin_44362628/article/details/124097524