You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ROS中同目录下Python文件/函数导入问题求助

ROS同目录Python文件导入失败:ImportError: cannot import name 'Sum' from 'sum'

我遇到了一个棘手的问题,和朋友都无法解决。我们通过示例talker.py和listener.py复现了该问题:无法从talker.py同目录下的其他Python文件中导入函数。

复现代码

仅需talker.py即可复现:

#!/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

sum.py代码:

#!/usr/bin/env python

def Sum(a,b):
     return a + b

CMakeLists.txt配置

我在CMakeLists.txt中添加的内容:

catkin_install_python(PROGRAMS
  scripts/talker.py scripts/listener.py scripts/sum.py
  DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)

错误输出

执行catkin_make、source devel/setup.bash、rosrun test talker.py后,得到以下输出:

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)

注:test是我的包名,目前无冲突。

已尝试的无效方法

  • 在sum.py中添加import rospy
  • 使用catkin build test替代catkin_make
  • 使用setup.py文件
  • 添加空白__init__.py文件(参考StackOverflow回答)

我现在毫无头绪,这似乎是个基础操作,恐怕我忽略了某些显而易见的点。经过大量搜索,发现大多问题都是跨包导入相关,未找到类似的简单场景案例。恳请提供帮助或提示!


内容的提问来源于stack exchange,提问作者J.V.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 21:01:36