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 (not the smartest name, but it doesn't conflict right now). Things I have tried (to no avail):
- add import rospy to the sum.py file
- use catkin build test instead of catkin_make
- use the setup.py file
- use a blank init.py file (per another answer on StackOverflow)
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 had 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!
I appreciate Andrei and John's help. Hopefully, this answer can help someone that stumbles upon the same importing issue.
I'm not quite sure what the underlying problem is, yet allow me to show the structure that removes the error:
CMakeLists.xtx:package.xmlsetup.pytalker.pyAnd most importantly, the file structure:
where I build with
catkin build, thensource devel/setup.bashandrosrun test_package talker.pyafter running an instance ofroscore. Given the location of the__init__.pyand thesetup.pyfile, I suspect something went wrong there initially.