LoginSignup
0
1

More than 3 years have passed since last update.

[ ROS ]他パッケージで作成したpythonモジュールをimportする方法

Last updated at Posted at 2021-05-28

はじめに

  • 2パターンあります
    • 簡単な方法: 簡単ですがゴチャゴチャします
    • 綺麗な方法: 手順が増えますが1行で済みます

簡単

import元

  • ディレクトリ構造
test/                           --- package
└── scripts                 
        └── test_import.py
├── CMakeLists.txt
├── package.xml
  • test_import.py
    • importできるかの確認用
test_import.py
import rospy
def called():
    rospy.loginfo("Success!")

import先

import os
import sys

import rospkg

rospack = rospkg.RosPack()
sys.path.append(os.path.join(rospack.get_path('test'),"scripts"))

from test.test_import import called

called()

きれい

ディレクトリ構造

  • 以下のような感じで
    • 必ずしもこうする必要はない
    • 下記のsetup.pyで調整
test/                           --- package
└── scripts                 
    └── test                    --- このフォルダ中のmoduleをimport 
        ├── __init__.py
        └── test_import.py
├── CMakeLists.txt
├── package.xml
├── setup.py                    --- 追加・編集(下記参照)

ファイル作成

  • test_import.py
    • importできるかの確認用
test_import.py
import rospy
def called():
    rospy.loginfo("Success!")
  • setup.py
    • packagesとpackage_dirは自分の環境に合わせる
setup.py
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup

d = generate_distutils_setup(
    packages=['test'],
    package_dir={'': 'scripts'}
)

setup(**d)

CMakeLists.txtの編集

  • 以下の2行を探してコメントを外す
CMakeListx.txt
catkin_python_setup()
catkin_package()
  • 最後にビルド
bash
$ catkin build

やってみよう

bash
$ python
>>> from test.test_import import called
>>> called()
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1