Android studio python plugin

Gradle pluginВ¶

Chaquopy is distributed as a plugin for Android’s Gradle-based build system. It can be used in any app which meets the following requirements:

In your project’s top-level build.gradle file, the Android Gradle plugin version ( com.android.tools.build:gradle ) should be between 3.6 and 7.0. Older versions as far back as 2.2 are supported by older versions of Chaquopy .

minSdkVersion must be at least 16. Older versions as far back as 15 are supported by older versions of Chaquopy .

Basic setupВ¶

Gradle pluginВ¶

In the project’s top-level build.gradle file, add the Chaquopy Maven repository and dependency to the end of the existing repositories and dependencies blocks:

Then, in the module-level build.gradle file (usually in the app directory), apply the Chaquopy plugin at the top of the file, but after the Android plugin:

All other configuration will be done in this module-level build.gradle . The examples below will show the configuration within defaultConfig , but it can also be done within a product flavor.

The Chaquopy plugin can also be used in an Android library module (AAR). However, it can only be used in one module in a project: either in the app module, or in exactly one library module. Attempting to use it in multiple modules will give the error “More than one file was found with OS independent path”.

ABI selectionВ¶

The Python interpreter is a native component, so you must use the abiFilters setting to specify which ABIs you want the app to support. The currently available ABIs are:

armeabi-v7a , supported by virtually all Android devices.

arm64-v8a , supported by most recent Android devices.

x86 , for the Android emulator.

x86_64 , for the Android emulator.

During development you’ll probably want to enable them all, i.e.:

There’s no need to actually install the NDK, as all of Chaquopy’s native libraries are already pre-compiled and stripped.

Each ABI will add several MB to the size of the app, plus the size of any native requirements . If you find this makes your app too large, see the FAQ .

buildPythonВ¶

Some features require Python 3.5 or later to be available on the build machine. These features are indicated by a note in their documentation sections.

By default, Chaquopy will try to find Python on the PATH with the standard command for your operating system, first with a matching minor version, and then with a matching major version. For example, if Chaquopy’s own Python version is 3.8.x, then:

On Linux and Mac it will try python3.8 , then python3 .

On Windows, it will try py -3.8 , then py -3 .

If this doesn’t work for you, set your Python command using the buildPython setting. For example, on Windows you might use one of the following:

DevelopmentВ¶

Source codeВ¶

By default, Chaquopy will look for Python source code in the python subdirectory of each source set. For example, the Python code for the main source set should go in src/main/python .

To include Python source code from other directories, use the android.sourceSets block. For example:

The setRoot method only takes effect on the standard Android directories. If you want to set the Python directory as well, you must do so explicitly, e.g.:

As with Java, it is usually an error if the source directories for a given build variant include multiple copies of the same filename. This is only permitted if the duplicate files are all empty, such as may happen with __init__.py .

StartupВ¶

It’s important to structure the app so that Python.start() is always called with an AndroidPlatform before attempting to run Python code. There are two basic ways to achieve this:

If the app always uses Python, then call Python.start() from a location which is guaranteed to run exactly once per process, such as Application.onCreate(). The easiest way to do this is to use PyApplication, or your own subclass of it. Simply add the following attribute to the element in AndroidManifest.xml :

Читайте также:  Главное меню этого андроида найти

Alternatively, if the app only sometimes uses Python, then call Python.start() after first checking whether it’s already been started:

RequirementsВ¶

This feature requires Python on the build machine, which can be configured with the buildPython setting.

External Python packages may be built into the app using the pip block in build.gradle . Within this block, add install lines, which can take any of the forms accepted by pip install. For example:

In our most recent tests, Chaquopy could install over 90% of the top 1000 packages on PyPI. This includes almost all pure-Python packages, plus a constantly-growing selection of packages with native components. To see which native packages are currently available, you can browse the repository here. To request a package to be added or updated, or for any other problem with installing requirements, please visit our issue tracker.

To pass options to pip install , give them as a comma-separated list to the options setting. For example:

Any options in the pip documentation may be used, except for those which relate to the target environment, such as —target , —user or -e . If there are multiple options lines, they will be combined in the order given.

Static proxy generatorВ¶

This feature requires Python on the build machine, which can be configured with the buildPython setting.

The static proxy feature allows a Python class to extend a Java class, or to be referenced directly in Java code or the AndroidManifest.xml file without going through the Java API.

To use this feature, write your Python classes using the syntax described in the “ Static proxy ” section, then list their containing modules in the build.gradle file as follows:

PackagingВ¶

Data filesВ¶

Any data files in your source code and requirements will be automatically built into your app. You can read them at runtime using a path relative to __file__ .

For example, if the data file is in the same directory as the Python file:

You can then pass the filename to open , or any other function which reads a file.

If the data file and the Python file are in different directories, then change the path accordingly. For example, if the Python file is alpha/hello.py , and the data file is bravo/filename.txt , then replace filename.txt above with ../bravo/filename.txt .

Do not write any files to these directories at runtime, as they may be deleted when the app is upgraded. Instead, write files to os.environ[«HOME»] , as described in the “ os ” section.

Data files within a top-level package (i.e. a top-level directory containing an __init__.py file) will not be available until the first time that package is imported. All other data files will be available as soon as Python has started.

Bytecode compilationВ¶

This feature requires Python on the build machine, which can be configured with the buildPython setting.

Your app will start up faster if its Python code is compiled to .pyc format, so this is enabled by default.

Compilation prevents source code text from appearing in stack traces, so during development you may wish to disable it. There are individual settings for:

stdlib : the Python standard library

For example, to disable compilation of your local source code:

In the case of src and pip , your buildPython must use the same bytecode format as Chaquopy itself. Usually this means it must have the same minor version, e.g. if Chaquopy’s own Python version is 3.8.x, then buildPython can be any version of Python 3.8.

If the bytecode formats do not match, the build will continue with a warning, unless you’ve explicitly set one of the pyc settings to true . Your app will still work, but its code will have to be compiled on the target device, which means it will start up slower and use more storage space.

Python standard libraryВ¶

Chaquopy supports the entire Python standard library, except for the modules listed below. If you discover a problem with any other module, please let us know.

Unsupported modulesВ¶

The following modules are unsupported because they require OS features which aren’t available on Android:

Читайте также:  Orbot для андроид инструкция

The following modules are unsupported because they require libraries which we don’t currently include:

multiprocessingВ¶

Because Android doesn’t support POSIX semaphores, most of the multiprocessing APIs will fail with the error “This platform lacks a functioning sem_open implementation”. The simplest solution is to edit your code to use multiprocessing.dummy instead.

os.environ[«HOME»] is set to your app’s internal storage directory. Any files or subdirectories created in this location will persist until the app is uninstalled.

If your app is debuggable, you can also read and write this directory from Android Studio using the Device File Explorer. Its path will be something like /data/data/your.application.id/files .

The ssl module is configured to use a copy of the CA bundle from certifi version 2021.5.30. The system CA store is not used.

sys.stdout and sys.stderr are redirected to the Logcat with the tags python.stdout and python.stderr respectively. The streams will produce one log line for each call to write() , which may result in lines being split up in the log. Lines may also be split if they exceed the Logcat message length limit of approximately 4000 bytes.

By default, sys.stdin always returns EOF. If you want to run some code which takes interactive text input, have a look at the console app template.

Android Studio pluginВ¶

To add Python editing suppport to the Android Studio user interface, you may optionally install the “Python Community Edition” plugin. However, Chaquopy isn’t integrated with this plugin, so you’ll see the warning “No Python interpreter configured for the module”, and your code will probably display many error indicators such as “Unresolved reference” and “No module named”. These are harmless: just go ahead and run your app, and if there really is an error, the details will be displayed in the Logcat.

Источник

Tools to run Python on Android

Jun 14, 2018 · 6 min read

Python has proven itself as a highly capable language — approachable for newcomers, but powerful in the hands of experts. Why shouldn’t you be able to use Python everywhere that you need to tell a computer to do something? And shouldn’t your tools exploit all the capabilities of Python as a language, not just the bits that map nicely to a C binding?

Modern computing doesn’t happen in an 80×25 console window. It happens on phones, tablets, and desktop machines with rich user interfaces. Shouldn’t you be able to use Python in all those locations, and exploit the unique capabilities of those platforms?

End users shouldn’t have to care what language their tools are written in. And that starts with looking and behaving like completely native tools. Native appearance, native behavior, delivered in the way a native app is delivered. Why shouldn’t your Python tools fit in just as well as a native tool?

There are several ways to use Python on Android.

1. BeeWare

BeeWare is a collection of tools for building native user interfaces

This is what BeeWare provides. Tools to help you write Python code with a rich, native user interface; and the libraries and support code necessary to get that code running on iOS, Android, macOS, Linux, Windows, tvOS, and more.

The Open Source development process has proven itself to be the most reliable way to develop robust and reliable software. That’s why the entire BeeWare suite of tools are BSD licensed, and available for all to use and modify.

2. Chaquopy

Chaquopy is a plugin for Android Studio’s Gradle-based build system.

Chaquopy enables you to freely intermix Java and Python in your app, using whichever language is best for your needs:

  • With the Python API , you can write an app partly or entirely in Python. The complete Android API and user interface toolkit are directly at your disposal.

Chaquopy works within Android’s standard build system:

  • If you use Android Studio, you can start using Chaquopy in 5 minutes with no change to your existing development process.
  • Download and installation are automated via Gradle.
  • Try out the demo app for Python 2 or Python 3.
  • Browse example source code on GitHub.
  • Or view the documentation.

3. Kivy

Kivy is a cross-platform OpenGL-based user interface toolkit.

You can run Kivy applications on Android, on (more or less) any device with OpenGL ES 2.0 (Android 2.2 minimum). This is standard on modern devices; Google reports the requirement is met by 99.9% of devices.

Читайте также:  Конструктор для андроид программирование

Kivy APKs are normal Android apps that you can distribute like any other, including on stores like the Play store. They behave properly when paused or restarted, may utilise Android services and have access to most of the normal java API as described below.

Follow the instructions below to learn how to package your app for Android, debug your code on the device, and use Android APIs such as for vibration and reading sensors.

The Kivy project provides all the necessary tools to package your app on Android, including building your own standalone APK that may be distributed on a market like the Play store. This is covered fully in the Create a package for Android documentation.

Using Android APIs

Although Kivy is a Python framework, the Kivy project maintains tools to easily use the normal java APIs, for everything from vibration to sensors to sending messages through SMS or email.

For new users, we recommend using Plyer. For more advanced access or for APIs not currently wrapped, you can use Pyjnius directly. Kivy also supplies an android module for basic Android functionality.

User contributed Android code and examples are available on the Kivy wiki.

4. Pyqtdeploy

P yqtdeploy is a tool for deploying PyQt applications. It supports deployment to desktop platforms (Linux, Windows and OS X) and to mobile platforms (iOS and Android).

pyqtdeploy works by taking the individual modules of a PyQt application, freezing them, and then placing them in a Qt resource file that is converted to C++ code by Qt’s rcc tool. Python’s standard library is handled in the same way.

pyqtdeploy also generates a Qt .pro file that describes all the generated C++ code. From this Qt’s qmake tool is used to generate a platform-specific Makefile which will then generate a single executable. Further Qt and/or platform specific tools can then be used to convert the executable to a platform specific deployable package.

pyqtdeploy requires PyQt5 and Python v3.2 or later to be installed.

PyQt4 and PyQt5 applications written using Python v2.6 and later and Python v3.3 and later are supported.

pyqtdeploy is released under the BSD license.

5. QPython

QPython is an on-device script engine and development environment.

In most cases, script can get your jobs done as good as the native application. Now you can make it with QPython’s help.

QPython is a script engine which runs Python programs on android devices. It also can help developers develop android applications.

QPython includes a complete development kit which help you to develop programs with mobile provides regular Python console

6. SL4A

SL4A (Scripting Layer for Android), originally named ASE (Android Scripting Environment), is a set of “facades” which expose a greatly-simplified subset of the Android API.

SL4A brings scripting languages to Android by allowing you to edit and execute scripts and interactive interpreters directly on the Android device. These scripts have access to many of the APIs available to full-fledged Android applications, but with a greatly simplified interface that makes it easy to get things done.

Scripts can be run interactively in a terminal and in the background. Python, Perl, JRuby, Lua, BeanShell, JavaScript, Tcl, and shell are currently supported, and we’re planning to add more. See the SL4A Video Help playlist on YouTube for various demonstrations of SL4A’s features.

SL4A is designed for developers and is alpha quality software.

7. PySide

PySide (the Python binding for the Qt toolkit) has some preliminary support for Android.

The PySide project provides LGPL-licensed Python bindings for the Qt 4. It also includes complete toolchain for rapidly generating bindings for any Qt-based C++ class hierarchies. PySide Qt bindings allow both free open source and proprietary software development and ultimately aim to support Qt platforms.

8.Termux

Termux is an Android terminal emulator and Linux environment app that works directly with no rooting or setup required. A minimal base system is installed automatically — additional packages are available using the APT package manager.

Источник

Оцените статью