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

如何在Android Studio中执行Python文件并实现Java与Python交互?

在Android Studio中从Java调用Python脚本并获取返回值的解决方案

嘿,你可能误解了Python Community Plugin的作用——它主要是帮你在Android Studio里编辑Python代码(比如语法高亮、代码补全),不是用来让Java直接调用并执行Python脚本的。下面给你两种靠谱的实现方案,顺便解决插件配置的问题:

一、正确配置Python Community Plugin(仅用于编辑Python代码)

如果你只是想用这个插件编辑x.py,按以下步骤配置Python SDK:

  • 打开Android Studio,点击顶部菜单栏的 File -> Settings(Windows/Linux)或 Android Studio -> Settings(Mac)
  • 在左侧导航栏找到 Languages & Frameworks -> Python SDK
  • 点击右上角的 + 号,选择你本地安装的Python解释器(比如系统里的Python 3.x),添加后应用设置
  • 如果找不到Python SDK选项:试试重启Android Studio,或者卸载重装Python Community Plugin,确保你的AS版本和插件版本兼容(推荐用AS稳定版,比如Arctic Fox及以上)

二、从Java调用Python脚本的两种可行方案

方案1:使用Chaquopy(推荐,简单高效)

Chaquopy是专门为Android设计的Python运行库,可以轻松在Java/Kotlin和Python之间交互:

  1. 配置项目依赖
    • 在项目根目录的build.gradle中添加Chaquopy仓库:
      buildscript {
          repositories {
              maven { url "https://chaquo.com/maven" }
          }
          dependencies {
              classpath "com.chaquo.python:gradle:14.0.2" // 可替换为最新版本号
          }
      }
      
    • 在app模块的build.gradle中应用插件并配置:
      plugins {
          id 'com.android.application'
          id 'com.chaquo.python'
      }
      
      android {
          defaultConfig {
              ndk {
                  abiFilters "armeabi-v7a", "arm64-v8a", "x86", "x86_64"
              }
              python {
                  // 如需安装Python第三方包,可在此配置
                  // pip { install "requests" }
              }
          }
      }
      
  2. 放置Python脚本
    在app/src/main目录下创建python文件夹,把你的x.py放进去,示例脚本:
    def process_input(input_str):
        # 这里写你的处理逻辑,示例返回大写后的字符串
        return input_str.upper()
    
  3. 在Java中调用并获取结果
    在y.java中编写调用代码:
    import com.chaquo.python.Python;
    import com.chaquo.python.android.AndroidPlatform;
    
    // 初始化Python环境(建议在Application类中执行一次)
    if (!Python.isStarted()) {
        Python.start(new AndroidPlatform(this));
    }
    
    // 获取Python实例并调用脚本方法
    Python py = Python.getInstance();
    String result = py.getModule("x").callAttr("process_input", "你要传递的字符串").toString();
    // result即为Python脚本返回的结果,可按需处理
    

方案2:手动通过Process调用Python解释器(无需第三方库)

如果不想依赖第三方库,你可以把Python解释器和脚本打包到APK,通过Java的ProcessBuilder执行:

  1. 准备文件
    • 下载适合Android的Python二进制文件(可通过交叉编译或找现成的安卓版Python),放到app/src/main/assets目录
    • 把x.py也放到app/src/main/assets目录
  2. 复制文件到可执行目录
    在Java中将assets里的文件复制到应用私有目录(assets为只读,需复制后才能执行):
    private void copyAssetsToLocal() {
        try {
            // 复制Python解释器
            InputStream is = getAssets().open("python3");
            File pythonFile = new File(getFilesDir(), "python3");
            OutputStream os = new FileOutputStream(pythonFile);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
            is.close();
            os.close();
            // 设置可执行权限
            pythonFile.setExecutable(true);
    
            // 复制Python脚本
            is = getAssets().open("x.py");
            File scriptFile = new File(getFilesDir(), "x.py");
            os = new FileOutputStream(scriptFile);
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
            is.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
  3. 执行脚本并获取结果
    private String runPythonScript(String inputStr) {
        try {
            ProcessBuilder pb = new ProcessBuilder(
                getFilesDir() + "/python3",
                getFilesDir() + "/x.py",
                inputStr // 传递给Python脚本的字符串参数
            );
            Process process = pb.start();
    
            // 读取Python脚本的输出结果
            BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream())
            );
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
            reader.close();
            process.waitFor();
            return result.toString();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    同时,x.py需要通过命令行参数接收输入,示例:
    import sys
    
    if __name__ == "__main__":
        input_str = sys.argv[1]
        # 自定义处理逻辑
        output = input_str.upper()
        print(output) # 输出结果,Java端会读取此打印内容
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 16:07:41