Pyscript1.py not working (IndentationError: unexpected indent)

Hello, when I enter python pyscript1.py I get the following message:

Traceback (most recent call last):
  File "pyscript1.py", line 1, in <module>
    from robot_control_class import RobotControl
  File "/home/user/catkin_ws/src/robot_control/robot_control_class.py", line 14
    if robot_name == "summit":
    ^
IndentationError: unexpected indent

I am not sure what has gone wrong in terms of indentation as I copied and pasted the code provided:

from robot_control_class import RobotControl

rc = RobotControl()

a = rc.get_laser(360)

print ("The distance measured is: ", a)

Thank you so much for your help!

1 Like

Hi @celenemeraz,

the code you copied seems ok, since the error is reported in the /home/user/catkin_ws/src/robot_control/robot_control_class.py file.

You have to check that robot_control_class.py file. If you have manually modified that file, please try to reset it (like copying its content again from where you initially copied it).

Please let us know if you have any other problems.

Hi @ralves, Unfortunately it did not work. I went back and copied again from the notebook, but I still get the same error code.

Could you paste here the content that you have in the robot_control_class.py file?

I’ve just followed the tutorial and it worked as expected in my case.

Could it be that your have a different (Chinese, arabic, etc) format instead of UTF-8?

Before and after pasting the content on robot_control_class.py, could you check the format enabled in the IDE?

If it is different, could you change it to UTF-8, just like what we have in the image below?

Hi @ralves
Yep, my format in the IDE is UTF-8. I’ve attached a screenshot and pasted the code on here as well. The same error is happening with the other code variables.py.
from robot_control_class import RobotControl

robotcontrol = RobotControl()

laser1 = robotcontrol.get_laser(0)
print ("The laser value received is: ", laser1)

laser2 = robotcontrol.get_laser(360)
print ("The laser value received is: ", laser2)

laser2 = robotcontrol.get_laser(719)
print ("The laser value received is: ", laser2)

Thank you so much for your help!!!

It looks like every time I try to see the output for any of the scripts, I get the same message.

Hi @celenemeraz,

just by looking at your screenshot, I can see that the code in your ~/catkin_ws/src/robot_control/robot_control_class.py is really badly formatted.

Can you see the difference when you compare your screenshot with mine?

Can you please copy the code below and paste on your robot_control_class.py file? Please, copy it on the robot_control_class.py file, not pyscript1.py.

#!/usr/bin/env python

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


class RobotControl():

    def __init__(self, robot_name="turtlebot"):
        rospy.init_node('robot_control_node', anonymous=True)

        if robot_name == "summit":
            rospy.loginfo("Robot Summit...")
            cmd_vel_topic = "/summit_xl_control/cmd_vel"
            # We check sensors working
            self._check_summit_laser_ready()
        else:      
            rospy.loginfo("Robot Turtlebot...")      
            cmd_vel_topic='/cmd_vel'
            self._check_laser_ready()

        # We start the publisher
        self.vel_publisher = rospy.Publisher(cmd_vel_topic, Twist, queue_size=1)
        self.cmd = Twist()        

        self.laser_subscriber = rospy.Subscriber(
            '/kobuki/laser/scan', LaserScan, self.laser_callback)
        self.summit_laser_subscriber = rospy.Subscriber(
            '/hokuyo_base/scan', LaserScan, self.summit_laser_callback)
        
        self.ctrl_c = False
        self.rate = rospy.Rate(1)
        rospy.on_shutdown(self.shutdownhook)

    
    def _check_summit_laser_ready(self):
        self.summit_laser_msg = None
        rospy.loginfo("Checking Summit Laser...")
        while self.summit_laser_msg is None and not rospy.is_shutdown():
            try:
                self.summit_laser_msg = rospy.wait_for_message("/hokuyo_base/scan", LaserScan, timeout=1.0)
                rospy.logdebug("Current /hokuyo_base/scan READY=>" + str(self.summit_laser_msg))

            except:
                rospy.logerr("Current /hokuyo_base/scan not ready yet, retrying for getting scan")
        rospy.loginfo("Checking Summit Laser...DONE")
        return self.summit_laser_msg

    def _check_laser_ready(self):
        self.laser_msg = None
        rospy.loginfo("Checking Laser...")
        while self.laser_msg is None and not rospy.is_shutdown():
            try:
                self.laser_msg = rospy.wait_for_message("/kobuki/laser/scan", LaserScan, timeout=1.0)
                rospy.logdebug("Current /kobuki/laser/scan READY=>" + str(self.laser_msg))

            except:
                rospy.logerr("Current /kobuki/laser/scan not ready yet, retrying for getting scan")
        rospy.loginfo("Checking Laser...DONE")
        return self.laser_msg

    def publish_once_in_cmd_vel(self):
        """
        This is because publishing in topics sometimes fails the first time you publish.
        In continuous publishing systems, this is no big deal, but in systems that publish only
        once, it IS very important.
        """
        while not self.ctrl_c:
            connections = self.vel_publisher.get_num_connections()
            if connections > 0:
                self.vel_publisher.publish(self.cmd)
                #rospy.loginfo("Cmd Published")
                break
            else:
                self.rate.sleep()

    def shutdownhook(self):
        # works better than the rospy.is_shutdown()
        self.ctrl_c = True

    def laser_callback(self, msg):
        self.laser_msg = msg

    def summit_laser_callback(self, msg):
        self.summit_laser_msg = msg

    def get_laser(self, pos):
        time.sleep(1)
        return self.laser_msg.ranges[pos]

    def get_laser_summit(self, pos):
        time.sleep(1)
        return self.summit_laser_msg.ranges[pos]

    def get_front_laser(self):
        time.sleep(1)
        return self.laser_msg.ranges[360]

    def get_laser_full(self):
        time.sleep(1)
        return self.laser_msg.ranges

    def stop_robot(self):
        #rospy.loginfo("shutdown time! Stop the robot")
        self.cmd.linear.x = 0.0
        self.cmd.angular.z = 0.0
        self.publish_once_in_cmd_vel()

    def move_straight(self):

        # Initilize velocities
        self.cmd.linear.x = 0.5
        self.cmd.linear.y = 0
        self.cmd.linear.z = 0
        self.cmd.angular.x = 0
        self.cmd.angular.y = 0
        self.cmd.angular.z = 0

        # Publish the velocity
        self.publish_once_in_cmd_vel()

    def move_straight_time(self, motion, speed, time):

        # Initilize velocities
        self.cmd.linear.y = 0
        self.cmd.linear.z = 0
        self.cmd.angular.x = 0
        self.cmd.angular.y = 0
        self.cmd.angular.z = 0

        if motion == "forward":
            self.cmd.linear.x = speed
        elif motion == "backward":
            self.cmd.linear.x = - speed

        i = 0
        # loop to publish the velocity estimate, current_distance = velocity * (t1 - t0)
        while (i <= time):

            # Publish the velocity
            self.vel_publisher.publish(self.cmd)
            i += 1
            self.rate.sleep()

        # set velocity to zero to stop the robot
        self.stop_robot()

        s = "Moved robot " + motion + " for " + str(time) + " seconds"
        return s


    def turn(self, clockwise, speed, time):

        # Initilize velocities
        self.cmd.linear.x = 0
        self.cmd.linear.y = 0
        self.cmd.linear.z = 0
        self.cmd.angular.x = 0
        self.cmd.angular.y = 0

        if clockwise == "clockwise":
            self.cmd.angular.z = -speed
        else:
            self.cmd.angular.z = speed

        i = 0
        # loop to publish the velocity estimate, current_distance = velocity * (t1 - t0)
        while (i <= time):

            # Publish the velocity
            self.vel_publisher.publish(self.cmd)
            i += 1
            self.rate.sleep()

        # set velocity to zero to stop the robot
        self.stop_robot()

        s = "Turned robot " + clockwise + " for " + str(time) + " seconds"
        return s


if __name__ == '__main__':
    
    robotcontrol_object = RobotControl()
    try:
        robotcontrol_object.move_straight()

    except rospy.ROSInterruptException:
        pass

Hi @ralves , Thank you for pointing that out. However, now I get another message saying the following:
File “robot_control_class.py”, line 191
pass
‘/hokuyo_base/scan’, LaserScan, self.summit_laser_callback)
SyntaxError: invalid syntax

Hi @celenemeraz,

The error message says the error is on line 191, but in the code that I asked you to copy there are only 181 lines, which means you probably pasted the code without removing the old code.

You have to make sure there is only the content I asked you to put there.

In the last case, I would recommend you start the course from the beginning and pay close attention to the error messages because they tell exactly what is wrong, always making sure you followed the instructions accordingly.

@ralves Is your suggestion only applicable to this script as I keep getting the same error for every new script I create under robot_control? Thank you.

Hi @celenemeraz,

if all your scripts have indentation problems, just try to recreate the files. This applies to all the files that are reported to have indentation problems.

Hi, I got the same issue in the exercise 2.2:
It seems wrong with the templated file, should we contact the Construct to update it:

" File “variables.py”, line 1, in
from robot_control_class import RobotControl
File “/home/user/catkin_ws/src/robot_control/robot_control_class.py”, line 13
if robot_name == “summit”:
^
IndentationError: unexpected indent"

Anyway, the course is awesome and more attractive than playing League of Legend. Thanks

I solved it by copying again the code then paste in the IDE, not the terminal.

2 Likes