rclpy: Accessing ros2 launch args from main function
I have a node in a package that I set up using ros2 pkg create --build-type ament_python --node-name my_node my_package
my_node.py
looks like this:
import rclpy
from rclpy.node import Node
class MyNode(Node):
def __init__(self, arg):
super().__init__("my_node")
self.arg = arg
def main(args = None):
rclpy.init(args = args)
node = MyNode(9)
node.get_logger().info("Hello from my_node")
try:
rclpy.spin(node)
except:
pass
node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
And my launch file looks like this:
from launch import LaunchDescription from launch_ros.actions import Node import launch
def generate_launch_description():
return LaunchDescription([
Node(
package='my_package',
node_namespace='test',
node_executable='my_node',
emulate_tty=True,
node_name='my_node',
),
launch.actions.DeclareLaunchArgument('arg1')
])
I am launching the node using ros2 launch -a ./launch/my_launch.py arg1:=9
How do I access arg1
from inside the main function? I want to use it to pass into the constructor of the Node.
Alternatively, is there another way to pass parameters into the main function? I just want to populate the args
in the def main(args = None)
function, but it needs to work when launched from a launch file.
Thanks