Note: This tutorial assumes that you have completed the previous tutorials: ROS tutorials.
(!) Please ask about problems and questions regarding this tutorial on answers.ros.org. Don't forget to include in your question the link to this page, the versions of your OS & ROS, and also add appropriate tags.

Setting Up Your PYTHONPATH

Description: What to do to find other python modules

Tutorial Level: BEGINNER

Next Tutorial: Using numpy with rospy

Contents

Commonly in python, when you use another python module, you use:

import foo

in your python code and it is up to the user of your code to make sure module "foo" is in his PYTHONPATH. In ROS, it is important that people can install multiple ROS libraries side-by-side on the same computer. That means there may be two different modules "foo", and the right one needs to be in the PYTHONPATH.

In ROS versions earlier than ROS Groovy, a library called roslib achieved this for us.

With catkin, python imports are done without roslib:

import foo

Catkin sets up PYTHONPATH in your catkin workspace and some relay files so that this works even with two python modules in your src folder. So if you have two modules in your catkin workspace, where one depends on the other, you need to configure and build the modules first, and then you can run them.

Example

For this example we create a new package and try to reuse the message Num that we defined in our beginner_tutorials package:

For catkin we create a new package in our source folder:

$ cd catkin_ws/src
$ catkin_create_pkg listener_extend rospy beginner_tutorials

Next we create a node using the message defined in beginner_tutorials. Create a diretory nodes first:

$ cd listener_extend
$ mkdir nodes

In the nodes directory, create a file listener_extend.py with these contents:

Toggle line numbers
   1 #!/usr/bin/env python
   2 import beginner_tutorials.msg
   3 num = beginner_tutorials.msg.Num()
   4 print(num)

Note that in comparison to rosbuild, no roslib call is required.

Make this file executable and run it:

$ chmod u+x nodes/listener_extend.py
$ python nodes/listener_extend.py
num: 0

If this fails,make sure you have run

$ source ~/catkin_ws/devel/setup.bash

before executing nodes/listener_extend.py

As you can see, the Num module of beginner_tutorials was successfully.


Wiki: rospy_tutorials/Tutorials/PythonPath (last edited 2019-10-03 21:56:06 by DirkThomas)