Android에서 Python파일 실행하기

참조 사이트

https://chaquo.com/chaquopy/doc/current/versions.html
https://www.youtube.com/watch?v=dFtxLCSu3wQ

버전에 맞게 minSdk, compileSdk, gradle version을 설정하여줍니다

프로젝트 build.gradle

buildscript {
    repositories {
        google()
        mavenCentral()
        maven { url "https://chaquo.com/maven" } //추가
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.0.0'
        classpath "com.chaquo.python:gradle:10.0.1" //추가

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

app build.gradle

plugins {
    id 'com.android.application'
}
apply plugin: 'com.android.application' //추가
apply plugin: 'com.chaquo.python' //추가
android {
    compileSdk 31

    defaultConfig {
        applicationId "com.example.chaquopy"
        minSdk 16 #버전에 맞게 변경
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        //여기부터 추가
        ndk { 
            abiFilters "armeabi-v7a", "x86"
        }
        python {
           pip{
                install "numpy"
            }
        }
        sourceSets {
            main {
                python.srcDir "src/main/python"
            }
        }
        //여기까지 추가 종료
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.4.0'
.
.
.
.
}

app/src/main 위치에 python 폴더 생성 후 파이썬 파일 업로드 또는 생성

MainActivity.class

        if (! Python.isStarted()) {
            Python.start(new AndroidPlatform(this));
            Python py = Python.getInstance();
            PyObject pyObject = py.getModule("파이썬파일 이름");

            PyObject obj = pyObject.callAttr("함수 이름");
            tv.setText(obj.toString());

        }

앱 실행해서 테스트

댓글 달기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

Scroll to Top