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

Android Studio集成Chaquopy报错:module 'time' has no attribute 'main'

问题解决步骤

1. 修复Python代码的语法错误

你的Python代码中return语句未缩进,会触发Python语法报错,修正后代码如下:

def main(num1, num2): #this is function definition
    numb1 = int(num1)
    numb2 = int(num2)
    pasha = numb1 + numb2
    return str(pasha)

2. 修正Java代码中的模块调用

错误核心是你调用了Python标准库的time模块,而非自己编写的Python模块,按以下方式修改:

  • 确认你在src/main/python目录下创建的Python文件名(比如文件名为calculator.py)
  • 将Java代码中getModule("time")的参数替换为你的Python文件名(不带.py后缀)

修正后的Java代码示例:

if(!Python.isStarted())
    Python.start(new AndroidPlatform(this));
Python pishi = Python.getInstance();
// 替换为你的Python文件名(不含.py)
PyObject pyobj = pishi.getModule("calculator");
PyObject obj = pyobj.callAttr("main",5,10);

Toast.makeText(this, obj.toString(), Toast.LENGTH_SHORT).show();

错误原因说明

Python标准库的time模块是系统自带工具模块,其中没有你定义的main函数,因此调用pyobj.callAttr("main")会触发AttributeError。只有加载你自己编写的Python模块,才能访问你定义的函数。

内容的提问来源于stack exchange,提问作者Abdul Rafay

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 02:45:38