【ROS】如何在ROS中使用anaconda虚拟环境?
先上结论:只需要在虚拟环境中安装以下几个包。
pip install rospkg rospy catkin_tools
以下是探索过程:
1. 建立测试的工作空间、软件包。
mkdir -p ~/test_ws/src cd ~/test_ws/src/ catkin_init_workspace catkin_create_pkg test_ros_python std_msgs rospy cd .. catkin_make echo "source ~/test_ws/devel/setup.bash" >> ~/.bashrc source ~/.bashrc
创建测试代码。
roscd test_ros_python/ mkdir scripts touch test_ros_python.py chmod +x test_ros_python.py
其中的内容来自官方教程中。
#!/usr/bin/env python # license removed for brevity import rospy from std_msgs.msg import String def talker(): pub = rospy.Publisher(chatter, String, queue_size=10) rospy.init_node(talker, anonymous=True) rate = rospy.Rate(10) # 10hz while not rospy.is_shutdown(): hello_str = "hello world %s" % rospy.get_time() rospy.loginfo(hello_str) pub.publish(hello_str) rate.sleep() if __name__ == __main__: try: talker() except rospy.ROSInterruptException: pass#!/usr/bin/env python # license removed for brevity import rospy from std_msgs.msg import String def talker(): pub = rospy.Publisher(chatter, String, queue_size=10) rospy.init_node(talker, anonymous=True) rate = rospy.Rate(10) # 10hz while not rospy.is_shutdown(): hello_str = "hello world %s" % rospy.get_time() rospy.loginfo(hello_str) pub.publish(hello_str) rate.sleep() if __name__ == __main__: try: talker() except rospy.ROSInterruptException: pass
2. 在原生环境下运行。
roscore # 在新的终端下 rosrun test_ros_python test_ros_python.py
得到下图结果,运行正常。
3. 使用原生环境没有的包。
代码增加使用scipy,这是在原生环境下没有的包,可类比于其它任何包。
#!/usr/bin/env python # license removed for brevity import rospy from std_msgs.msg import String from scipy import constants print(constants.pi) def talker(): pub = rospy.Publisher(chatter, String, queue_size=10) rospy.init_node(talker, anonymous=True) rate = rospy.Rate(10) # 10hz while not rospy.is_shutdown(): hello_str = "hello world %s" % rospy.get_time() rospy.loginfo(hello_str) pub.publish(hello_str) rate.sleep() if __name__ == __main__: try: talker() except rospy.ROSInterruptException: pass#!/usr/bin/env python # license removed for brevity import rospy from std_msgs.msg import String from scipy import constants print(constants.pi) def talker(): pub = rospy.Publisher(chatter, String, queue_size=10) rospy.init_node(talker, anonymous=True) rate = rospy.Rate(10) # 10hz while not rospy.is_shutdown(): hello_str = "hello world %s" % rospy.get_time() rospy.loginfo(hello_str) pub.publish(hello_str) rate.sleep() if __name__ == __main__: try: talker() except rospy.ROSInterruptException: pass
同样地进行测试。
roscore # 在新的终端下 rosrun test_ros_python test_ros_python.py
得到下图结果,运行报错。
4. 创建虚拟环境并测试。
conda create -n test-ros-python python=3.6 conda activate test-ros-python roscore # 在新的终端下 rosrun test_ros_python test_ros_python.py
得到下图结果,并不能成功运行ros。
于是来到最为重要的一步,安装以下几个ROS必须的包。
pip install rospkg rospy catkin_tools
然后再次运行得到下图结果,找不到scipy包。
安装scipy。
pip install scipy
再次运行,成功!