Robotics StackExchange | Archived questions

Calling a local python script from a python launch file

Using Foxy on Ubuntu 20.04:

I have a bringup package with multiple launch files and I am trying to put some common functionality (a few methods) in a utils.py python script.

launch directory: launchfile1.py launchfile2.py utils.py init.py # added because some answers to similar questions on the net suggested it could help. It didn't...

I haven't find any way to import my utils.py methods in the launch files but Python3 makes it very difficult to import relative modules and added a lot of rules.

I tried multiple syntaxes:

from utils import method1
# fails with: ModuleNotFoundError: No module named 'utils'
# Probably fails because this is not an installed module

from .utils import method1
# fails with: ImportError: attempted relative import with no known parent package

from .utils.py import method1
# fails with: ImportError: attempted relative import with no known parent package

It would be bizarre not to allow for such basic functionality. As a workaround, I am copying all my helper methods to every single launch file...

Asked by ohf on 2021-08-05 10:21:57 UTC

Comments

Have the same exact question. Someone please respond.

Asked by spoluri on 2021-10-20 17:12:53 UTC

Answers

Try adding this to your launch file:

import os
import sys
dir_path = os.path.dirname(os.path.realpath(__file__))
sys.path.append(dir_path)
from utils import method1

Asked by tnajjar on 2022-01-10 17:41:59 UTC

Comments

Thanks, I had exactly the same issue and this resolved it!!

Asked by leander on 2022-07-07 04:24:24 UTC