How to import modules using ros noetic with python3?
Hello, I'm new in ROS. When using ROS noetic with python, I can't import any modules in the same directory. For example, I created a package "test" and wrote two test files under ".../test/src/" as followed:
test1.py:
#!/usr/bin/env python
import sys
print(sys.path)
from test2 import *
a=test()
print(math.pi*2)
test2()
test2.py:
#!/usr/bin/env python
import math
class test:
def __init__(self):
print(math.pi)
def test2():
print('test')
After executing 'rosrun test test1.py', the result shows:
['/home/mu/mu/devel/lib/test', '/home/mu/mu/devel/lib/python3/dist-packages', '/opt/ros/noetic/lib/python3/dist-packages', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/mu/.local/lib/python3.8/site-packages', '/usr/local/lib/python3.8/dist-packages', '/usr/lib/python3/dist-packages']
Traceback (most recent call last):
File "/home/mu/mu/devel/lib/test/test1.py", line 15, in <module>
exec(compile(fh.read(), python_script, 'exec'), context)
File "/home/mu/mu/src/test/src/test1.py", line 6, in <module>
from test2 import *
ModuleNotFoundError: No module named 'test2'
But the same files executed in ROS melodic show:
test2 is imported
['/home/mu/mu/src/test/src', '/home/mu/mu/devel/lib/python2.7/dist-packages', '/opt/ros/melodic/lib/python2.7/dist-packages', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/home/mu/.local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/wx-3.0-gtk3']
3.14159265359
6.28318530718
test
I noticed sys.path[0] was different. So how to change sys.path[0], or how to import modules correctly in ROS noetic?