Search code examples
python-2.7ros

Python callback argument issue


I'm new to python. I have the following code:

#! /usr/bin/env python

import rospy
from sensor_msgs.msg import LaserScan
from geometry_msgs.msg import Twist

#defines a callback
def callback(msg):
    rospy.init_node('obstacle_avoidance')
    pub = rospy.Publisher('/cmd_vel', Twist, queue_size=10)
    rate = rospy.Rate(1)

    while not rospy.is_shutdown():
        print('==================================')

        print('CHECKING .....')
        print msg.ranges


if __name__ == '__main__':
    try:
        callback()
    except rospy.ROSInterruptException:
        pass

With the following response:

TypeError: callback() takes exactly 1 argument (0 given)

I understand what the error is saying but the msg variable is not one I defined so I'm not sure what to pass.


Solution

  • You seem to be combining 2 tutorials in a way that doesn't work. You call callback() but don't provide an argument which makes it crash because callback() expects an argument.

    You then use msg.ranges in your function. (which is a Laser message idea).

    You should probably do something like this

    #! /usr/bin/env python
    
    import rospy
    from sensor_msgs.msg import LaserScan
    from geometry_msgs.msg import Twist
    
    #defines a callback
    def callback(msg):
        while not rospy.is_shutdown():
            print('==================================')
            print('CHECKING .....')
            print msg.ranges
    
    
    if __name__ == '__main__':
        try:
            rospy.init_node('obstacle_avoidance')
            pub = rospy.Publisher('/cmd_vel', Twist, queue_size=10)
            rospy.Subscriber('/base_scan', LaserScan, callback)
        except rospy.ROSInterruptException:
            pass