Chaquopy:实现Android与Python交互

Chaquopy 是开源免费使用,商用收费的一款SDK,主要用于实现Java与Python交互,可以应用于Android应用当中。 那么下面我们就来看一下,如何实现Android与Python的交互调用吧。

最新版本是12.0.0

Chaquopy官网

开发文档

一、支持AGP版本和Python运行版本

通过查看Change Log得知,各版本的Chaquopy对AGP(Android Gradle Plugin)的支持程度,汇总成表格如下:

版本 AGP版本 弃用不支持 Python版本
12.0.0 (2022-05-12) 7.2 4.0 3.8.13
11.0.0 (2022-02-01) 7.1 3.6
10.0.1 (2021-09-22) 4.2-7.0 3.4,3.5 3.8.11
9.1.0 (2021-01-02) - - -
9.0.0 (2020-11-06) 4.1 3.3 3.8.6
8.0.1 (2020-07-28) - -
8.0.0 (2020-06-15) 4.0 3.2 3.8.3

9.1.0和8.0.0未标明,应该是向下兼容的

二、新建Android工程配置环境

  1. 根目录settings.gradle文件添加
maven { url "https://chaquo.com/maven" }
复制代码
  1. 项目的build.gradle添加

id 'com.chaquo.python' version '12.0.0' apply false
复制代码
  1. app里面的build.gradle中添加

id 'com.chaquo.python'
复制代码
  1. 然后在app里面的build.gradle中的defaultConfig中添加

ndk {
    abiFilters "armeabi-v7a", "arm64-v8a", "x86", "x86_64"
}
复制代码
  1. 然后页面会出现黄色提示框,点击Sync Now或者gragle的小图标,同步完成之后,Chaquopy就加进项目里面来了,还需要配置python的编译执行环境。

  1. 配置python的环境,还是在defaultConfig中添加,buildPython配置python的可执行程序路径,图示是Windows的,但没有指向具体的路径,需要根据个人电脑上安装的python环境来配置,如果没有python环境,还要先去安装python,我的电脑是mac,最终设置的是/usr/bin/python3

python {
    buildPython "/usr/bin/python3"
//  buildPython "C:/path/to/python.exe"
}
复制代码
  1. 安装python的包,示例如下
defaultConfig {
    python {
        pip {
            // A requirement specifier, with or without a version number:
            install "scipy"
            install "requests==2.24.0"

            // An sdist or wheel filename, relative to the project directory:
            install "MyPackage-1.2.3-py2.py3-none-any.whl"

            // A directory containing a setup.py, relative to the project
            // directory (must contain at least one slash):
            install "./MyPackage"

            // "-r"` followed by a requirements filename, relative to the
            // project directory:
            install "-r", "requirements.txt"
        }
    }
}
复制代码
  1. python代码文件放置位置在src/main下面的python目录

9.python目录下创建一个hello.py文件,然后添加代码

def sayHello():
    print("Hello World")
复制代码

10.在MainActivity中添加调用python的代码

if (!Python.isStarted()){
    Python.start(new AndroidPlatform(this));
}
Python python=Python.getInstance();
PyObject pyObject=python.getModule("hello");
pyObject.callAttr("sayHello");
复制代码

虽然官网推荐用Application继承PyApplication,但是我们可以看到PyApplicaiton中启作用的命令就一句,况且我们项目一般都会引入分包的Application,所以直接调用代码加载python环境更合适。

将代码运行起来后,我们可以在Logcat中看到python输出的语句

说明Android已经成功调用到python了,后续更多内容,请查看官网的开发文档。

如果你在使用过程中,遇到什么问题,欢迎回复来互相交流。

猜你喜欢

转载自juejin.im/post/7104465131723030564