choose random items from python file and send to launch file

asked 2020-11-03 21:14:13 -0500

Jason-Zhou1 gravatar image

Hi all, I want to randomly choose 2 items from a list[banana,apple,pear,mango,orange] in a python file (rand_choose.py). Then I need to pass these 2 items to a launch file (choose_fruit.launch.xml) and assign them to two strings "first" and "last". My operation system is ROS2 eloquent in Ubuntu18.04. May I know how to fulfill it? Thank you!

edit retag flag offensive close merge delete

Comments

Can you elaborate on your intentions? normally you do something like this programmatically in your node. you can also launch a launchfile with arguments, maybe that's what you're looking for.

crnewton gravatar image crnewton  ( 2020-11-10 05:01:55 -0500 )edit

from random import seed

from random import choice

import rclpy

from rclpy.node import Node

class GenParams(Node):

seed(1)

array = [banana,apple,pear,mango,orange]

for _ in range(2):

selection = choice(array)

print(selection)

def __init__(self):

super().__init__('gen_params_rclpy')

self.declare_parameter('rand_fruit')

rand_fruit = selection

print(rand_fruit)

def main(args=Node):

rclpy.init(args=args)

node = TestParams()

rclpy.spin(node)

node.destroy_node()

rclpy.shutdown()

if __name__==”__main__”:

main()

Jason-Zhou1 gravatar image Jason-Zhou1  ( 2020-11-11 17:54:46 -0500 )edit

<launch>

< param name="rand_fruit" command="$(find fruit_pkg)/scripts/rand_choose.py"/>

</launch>

Jason-Zhou1 gravatar image Jason-Zhou1  ( 2020-11-11 18:00:10 -0500 )edit

When I launch the choose_fruit file, i got error messages:

Caught exception when trying to load file of format [xml]:Caught exception when trying to load file of format [xml]: not well-formed (invalid token): line 4, column 1

May I know how to improve it to be workable? Thanks!

Jason-Zhou1 gravatar image Jason-Zhou1  ( 2020-11-11 18:02:11 -0500 )edit

Related files: rand_choose.py:

from random import seed

from random import choice

import rclpy

from rclpy.node import Node

class GenParams(Node):

    seed(1)

    array = [banana,apple,pear,mango,orange]

    for _ in range(2):

            selection = choice(array)

            print(selection)

    def __init__(self):

            super().__init__('gen_params_rclpy')

            self.declare_parameter('rand_fruit')

            rand_fruit = selection

            print(rand_fruit)

def main(args=Node):

      rclpy.init(args=args)

      node = TestParams()

      rclpy.spin(node)

      node.destroy_node()

      rclpy.shutdown()

if __name__==”__main__”:

      main()

choose_fruit.launch.xml:

<launch>

      < param name="rand_fruit" command="$(find fruit_pkg)/scripts/rand_choose.py"/>

</launch>
Jason-Zhou1 gravatar image Jason-Zhou1  ( 2020-11-16 03:01:44 -0500 )edit

Please advise what's the problem in above files and how to make them workable in ros2. Thanks!

Jason-Zhou1 gravatar image Jason-Zhou1  ( 2020-11-16 03:06:16 -0500 )edit