ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | Q&A
Ask Your Question

ROS python version SyntaxError: invalid syntax

asked 2020-07-12 11:38:53 -0600

JustANoob gravatar image

I have a syntax error, but i could not solve it, need help

error: for k, g in groupby(enumerate(ranges), lambda (i,x):i-x):

Also, 1 question if anyone is able to help me i am using Ubuntu 18.04, i rosrun this file but got error showing : [rosrun] Couldn't find executable named below /home/sk/catkin_ws/src/testbot_description

is it because of the ROS python version i am using that caused the error?

the following is the code:

#!/usr/bin/env python

import rospy
from std_msgs.msg import String
import sensor_msgs.msg
import random
import numpy as np
from geometry_msgs.msg import Twist
from itertools import *
from operator import itemgetter

LINX = 0.0 #Always forward linear velocity.
THRESHOLD = 1.5 #THRESHOLD value for laser scan.
PI = 3.14
Kp = 0.05
angz = 0

def LaserScanProcess(data):
    range_angels = np.arange(len(data.ranges))
    ranges = np.array(data.ranges)
    range_mask = (ranges > THRESHOLD)
    ranges = list(range_angels[range_mask])
    max_gap = 40
    # print(ranges)
    gap_list = []
    for k, g in groupby(enumerate(ranges), lambda (i,x):i-x):
        gap_list.append(map(itemgetter(1), g))
    largest_gap = gap_list[-1]
    min_angle, max_angle = largest_gap[0]*((data.angle_increment)*180/PI), largest_gap[-1]*((data.angle_increment)*180/PI)
    average_gap = (max_angle - min_angle)/2

    turn_angle = min_angle + average_gap

    print(min_angle, max_angle)

    global LINX
    global angz
    if average_gap < max_gap:
        angz = -0.5
        LINX = 0.5
        angz = Kp*(-1)*(90 - turn_angle)

def main():
    rospy.init_node('listener', anonymous=True)

    pub = rospy.Publisher('/cmd_vel', Twist, queue_size=10)
    rospy.Subscriber("scan", sensor_msgs.msg.LaserScan , LaserScanProcess)

    rate = rospy.Rate(10) # 10hz

    while not rospy.is_shutdown():
        command = Twist()
        command.linear.x = LINX
        command.angular.z = angz

if __name__ == '__main__':
edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2021-07-27 01:24:55 -0600

I think its because in Python 3, print statement has been replaced with a print() function, with keyword arguments to replace most of the special syntax of the old print statement. But if you write this in a program and someone using Python 2.x tries to run it, they will get an error. To avoid this, it is a good practice to import print function:

from __future__ import print_function

Now your code works on both python2 and python3

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2020-07-12 10:07:41 -0600

Seen: 876 times

Last updated: Jul 12 '20