0
$\begingroup$

Rosanswers logo

I'd like to have a python module globally available across all nodes in a catkin workspace. It contains functions that I don't want to repeat in every module I need them. They are pure Python modules. I'd like to do something like this:

#!/usr/bin/env python
# mymodule.py

def myFunction(a):
  # just an example
  something = a * 2
  return something

# End of mymodule.py

And in my ROS Python scripts I'd like to be able to import that module like...

#!/usr/bin/env python
import roslib...
import mymodule

def someotherfunc():
  b = mymodule.myFunction(10)

if __name__ ==...

It shall be available in my whole catkin workspace. Where do I have to put it?

Thanks a lot!


Originally posted by Hendrik Wiese on ROS Answers with karma: 1145 on 2013-08-02

Post score: 0

$\endgroup$

1 Answer 1

0
$\begingroup$

Rosanswers logo

I think this tutorial covers what you would like to do:

summary:

1. Create setup.py in your package root directory with these contents (where <python_mod> is replaced by the name of your python module, typically the same name as your catkin package)

## ! DO NOT MANUALLY INVOKE THIS setup.py, USE CATKIN INSTEAD

from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup

# fetch values from package.xml
setup_args = generate_distutils_setup(
    packages=['<python_mod>'],
    package_dir={'': 'src'},
    requires=['std_msgs', 'rospy'])
)

setup(**setup_args)

2. Add the following line to your CMakeLists.txt

catkin_python_setup()

3. Create a directory for your python scripts (if you have any python executables)

mkdir <pkg_root>/scripts

4. Create a directory for your python modules

mkdir <pkg_root>/src/<python_mod>/

5. Add an empty __init__.py to your python module directory

touch <pkg_root>/src/<python_mod>/__init__.py

6. create your python mod

touch <pkg_root>/src/<python_mod>/mod1.py

You should now be able to import this module as

import python_mod.mod1


Hope that helps!

Reference the tutorial for details.


Originally posted by dPackard with karma: 115 on 2013-08-02

This answer was ACCEPTED on the original site

Post score: 1


Original comments

Comment by Hendrik Wiese on 2013-08-06:
Yeah, works like a charm! Thanks a lot! :-)

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.