Call Python from Kotlin or embed Python code inside Kotlin

Submitted by Dickens A S on Fri, 11/22/2019 - 11:47

Embedded Python inside Kotlin

Compile and Execute from MSYS2 or Cygwin with python development C header files
 

Demo output

Embed Python

Python code which is running inside Kotlin

def multiply(a,b):
    print("Will compute", a, "times", b)
    c = 0
    for i in range(0, a):
        c = c + b
    return c

Make sure you set environment variable PYTHONPATH and PYTHONHOME properly in MSYS or Cygwin

export PYTHONPATH=./:/mingw64/lib/python3.7
export PYTHONHOME=/mingw64/lib/python3.7/

Kotlin code which runs python

package plot

import python.*
import kotlinx.cinterop.*

fun main(args: Array<String>) = memScoped {

    Py_SetProgramName(null)
    Py_Initialize()
    
    //Direct python script embedding
    
    PyRun_SimpleStringFlags(

"""
from time import time,ctime
print('Today is',ctime(time()))
"""

,null)

    
    //External python code located in PYTHONPATH

    //#load module multiply or multiply.py from PYTHONPATH
    var pName = PyUnicode_DecodeFSDefault("multiply")
    var pModule = PyImport_Import(pName)
    
    //#load python function named "multiply" from the code
    var pFunc = PyObject_GetAttrString(pModule, "multiply")
    var pArgs = PyTuple_New(2L)
    
    //#set 2 parameters for the python method
    PyTuple_SetItem(pArgs, 0L, PyLong_FromLong(3))
    PyTuple_SetItem(pArgs, 1L, PyLong_FromLong(3))
    
    //#call the python method and get the result value
    var pValue = PyObject_CallObject(pFunc, pArgs)
    println("Result of call: " + PyLong_AsLong(pValue));
    
    Py_Finalize()
}

MSYS2

This is required for windows to download pre-compiled libraries and its headers

pacman -S python libgpgme-python3 mingw-w64-x86_64-python3-numpy mingw-w64-x86_64-python3 mingw-w64-x86_64-libftdi 

change x86_64 to i686 for 32 bit widows

Source Code

 

Add new comment