ros2 / rclpy

rclpy (ROS Client Library for Python)
Apache License 2.0
289 stars 224 forks source link

[Bug] error when node created with rclpy.node.Node #1301

Closed sasilva1998 closed 3 months ago

sasilva1998 commented 3 months ago

Bug report

Required Info:

Steps to reproduce issue

import rclpy
# import tf2_ros

class Test(rclpy.node.Node):
    def __init__(self):
        super().__init__("test_node")
        self.timer = self.create_timer(1.0, self.log_message)

    def log_message(self):
        self.get_logger().info("Node running")

def main(args=None):
    rclpy.init(args=args)
    test_node = Test()
    rclpy.spin(test_node)
    test_node.destroy_node()
    rclpy.shutdown()

if __name__ == "__main__":
    main()

Expected behavior

The node should be spinning and printing the following message:

[INFO] [1718709806.801412572] [test_node]: Node running
[INFO] [1718709807.801320774] [test_node]: Node running
[INFO] [1718709808.801408902] [test_node]: Node running

Actual behavior

An error is obtained and the node crashes:

Traceback (most recent call last):
  File "/home/sasm/ros/humble/system/install/lib/grid_planners_demo/test", line 33, in <module>
    sys.exit(load_entry_point('grid-planners-demo', 'console_scripts', 'test')())
  File "/home/sasm/ros/humble/system/install/lib/grid_planners_demo/test", line 25, in importlib_load_entry_point
    return next(matches).load()
  File "/usr/lib/python3.10/importlib/metadata/__init__.py", line 171, in load
    module = import_module(match.group('module'))
  File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/home/sasm/ros/humble/system/build/grid_planners_demo/grid_planners_demo/test.py", line 6, in <module>
    class Test(rclpy.node.Node):
AttributeError: module 'rclpy' has no attribute 'node'
[ros2run]: Process exited with failure 1

Additional information

If line 2 (import tf2_ros) is uncommented, the node works properly.

clalancette commented 3 months ago

This is the way it works; by default, python doesn't recursively import. You should do import rclpy.node to get access to the Node object. Also see all of our documentation, which does something similar.