Need help: publish and subscrib python

Hey guy’s!

I need some help with a Python program, I am now in the 5 days basic ROS program and I’m having truble with exercise 4.3 (Topics quiz).

In the Python program I want to publish to ‘/cmd_vel’ and I want to subscribe to ‘/kobuki/laser/scan’.

Every time I run it I have this error:

Python program:

#! /usr/bin/env python

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


rospy.init_node('topics_quiz_node')
pub = rospy.Publisher('/cmd_vel', Twist, queue_size=1)
rate = rospy.Rate(2)


move = Twist()
move.linear.x = 0 
move.angular.z = 0



while not rospy.is_shutdown(): 

    def callback(msg): 
        print(msg)

    sub = rospy.Subscriber('/kobuki/laser/scan', LaserScan, callback)

    pub.publish(move)
    rate.sleep()

When I comment out the sub = rospy. … and def callback then the program works.

Launch file:
< launch>
< !-- my package launch file →
< node pkg=“topics_quiz” type=“my_script.py” name=“topics_quiz_node” output=“screen”>
< node/>
< /launch>

Thank you for helping me!

afbeelding

The error message suggests it’s a formatting/indenting error. Maybe unindent and re-indent the code?

/K

2 Likes

Hi
I think problem is in this section of code

while not rospy.is_shutdown():

def callback(msg): 
    print(msg)

sub = rospy.Subscriber('/kobuki/laser/scan', LaserScan, callback)

Because You are redefining the callback in every run of the while loop and that is not a good practice. Instead try this

sub = rospy.Subscriber(’/kobuki/laser/scan’, LaserScan, callback)

def callback(msg):
print(msg)

while not rospy.is_shutdown():

pub.publish(move)
rate.sleep()
1 Like

@cmiguelezmachado I thought about mentioning that, but the error message seems to be about indentation. But I agree - not the best practice.
/K

1 Like

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.