Importing python files/functions from the same directory (as simple as it sounds!)
Hello everyone,
I've managed to run in an incredible issue that me and my friend just are not able to solve. Luckily, we managed to replicate the issue in the example talker.py
and listener.py
. My issue is that I cannot seem to import any function from another python file, even when these files are located in the same folder as the talker.py
file.
Here is the code (you just need talker.py for this):
#!/usr/bin/env python
import rospy
from sum import Sum
from std_msgs.msg import String
def talker():
pub = rospy.Publisher('chatter', String, queue_size=10)
print(Sum(1,2))
rospy.init_node('talker', anonymous=True)
rate = rospy.Rate(10) # 10hz
while not rospy.is_shutdown():
hello_str = "hello world %s" % rospy.get_time()
rospy.loginfo(hello_str)
pub.publish(hello_str)
rate.sleep()
if __name__ == '__main__':
try:
talker()
except rospy.ROSInterruptException:
pass
the sum.py:
#!/usr/bin/env python
def Sum(a,b):
return a + b
And what I have added to the CMakeLists.txt file:
catkin_install_python(PROGRAMS
scripts/talker.py scripts/listener.py scripts/sum.py
DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)
after doing catkin_make
, source devel/setup.bash
, and rosrun test talker.py
I get the output:
Traceback (most recent call last):
File "/home/-/catkin_ws/devel/lib/test/talker.py", line 15, in <module>
exec(compile(fh.read(), python_script, 'exec'), context)
File "/home/-/catkin_ws/src/test/scripts/talker.py", line 40, in <module>
from sum import Sum
ImportError: cannot import name 'Sum' from 'sum' (/home/-/catkin_ws/devel/lib/test/sum.py)
where test
is the name that I gave the package.
Things I have tried (to no avail):
- add
import rospy
to thesum.py
file - use
catkin build test
instead ofcatkin_make
- use the
setup.py
file - use a blank
__init__.py
file
I'm quite frankly at a loss on what to do. It seems like such a fundamental thing to do, that I'm afraid I'm missing something extremely obvious. However, after a lot of search engine work, it seems that no one has such as simple problem before (most of what I find relates to importing functions/files/modules from different packages etc.)
Any help or hints would be really appreciated!
Cheers!