问题解决:Ubuntu中【无法运行python程序】——系统显示存在未预期的符号‘(’

问题解决:Ubuntu中【无法运行python程序】,系统显示存在未预期的符号‘(’

一、问题

  1. Ubuntu终端之中无法运行python程序。系统显示存在“未预期的符号‘(’附近有语法错误”(如下图所示)
    在这里插入图片描述

二、环境:

  1. Ubuntu 16.04

三、解决办法:

备注:
步骤1:运行程序
步骤2:解决办法

  1. 首先,附上我的程序。该程序作用为实现ROS海龟程序中的话题发布。
import rospy
from geometry_msgs.msg import Twist

def velocity_publisher():
    rospy.init_node('velocity_publisher',anonymous=True)    
    turtle1_vel_pub=rospy.Publisher('/turtle1/cmd_vel',Twist,queue_size=10)

    rate=rospy.Rate(10)
    
    while not rospy.is_shutdown(): 
           
             vel_msg=Twist()
             vel_msg.linear.x=0.5
             vel_msg.angular.z=0.2
             
             
             turtle1_vel_pub.publish(vel_msg)
             rospy.loginfo("Publish turtle velocity command[%0.2f m/s , %0.2f rad/s]",
                                    vel_msg.linear.x,vel_msg.angular.z)

             
             rate.sleep()

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

  1. 以上程序在python中直接运行,并没有报错,但是当我在终端中运行时,就出现了“存在未预期的符号‘(’”的错误。
    我查找许多方法,比如括号前加入‘’,但是都没有解决这个问题。
    最后我求助了学校老师(感谢老师!)
    发现只需要在文件的最开头加入:#!/usr/bin/env python,程序就可以运行成功了。(如下图所示)
#!/usr/bin/env python

import rospy
from geometry_msgs.msg import Twist

3.最后检讨一下出现以上问题的原因。
本来在范例程序中是包含#后的内容的,但是我以为在python中#后的都是注释内容,所以自己在写的时候就把#后的内容都去掉了,因此造成了程序无法运行。
类似的还有 # -- coding: utf-8 -- 。
所以大家可以在ubuntu编写python程序时,把这两行直接加在最前面。

 #!/usr/bin/env python
 # -*- coding: utf-8 -*- 

引用:

1.【古月居】古月·ROS入门21讲 | 一学就会的ROS机器人入门教程:https://www.bilibili.com/video/BV1zt411G7Vn?p=10
2. https://answers.ros.org/question/306065/error-on-import-ros-packages/

猜你喜欢

转载自blog.csdn.net/qq_41940277/article/details/122722322
今日推荐