标签归档:jython

在Java中调用Python?

问题:在Java中调用Python?

我想知道是否可以使用jython从Java代码调用python函数,还是仅用于从python调用Java代码?

I am wondering if it is possible to call python functions from java code using jython, or is it only for calling java code from python?


回答 0

Jython:适用于Java平台的Python- http ://www.jython.org/index.html

您可以使用Jython从Java代码轻松调用python函数。只要您的python代码本身在jython下运行,即不使用某些不受支持的c扩展名。

如果这对您有用,那肯定是您可以获得的最简单的解决方案。否则,您可以使用org.python.util.PythonInterpreter新的Java6解释器支持。

我的脑海中有一个简单的例子-但我希望它可以工作:(为简便起见,没有进行错误检查)

PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import sys\nsys.path.append('pathToModules if they are not there by default')\nimport yourModule");
// execute a function that takes a string and returns a string
PyObject someFunc = interpreter.get("funcName");
PyObject result = someFunc.__call__(new PyString("Test!"));
String realResult = (String) result.__tojava__(String.class);

Jython: Python for the Java Platform – http://www.jython.org/index.html

You can easily call python functions from Java code with Jython. That is as long as your python code itself runs under jython, i.e. doesn’t use some c-extensions that aren’t supported.

If that works for you, it’s certainly the simplest solution you can get. Otherwise you can use org.python.util.PythonInterpreter from the new Java6 interpreter support.

A simple example from the top of my head – but should work I hope: (no error checking done for brevity)

PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import sys\nsys.path.append('pathToModules if they are not there by default')\nimport yourModule");
// execute a function that takes a string and returns a string
PyObject someFunc = interpreter.get("funcName");
PyObject result = someFunc.__call__(new PyString("Test!"));
String realResult = (String) result.__tojava__(String.class);

回答 1

嘿,我想我会输入我的答案,尽管已经很晚了。我想首先要考虑一些重要的事情,即您希望在java和python之间建立多强的连接。

首先 ,您是否只想调用函数,或者您是否真的希望python代码更改Java对象中的数据?这个非常重要。如果您只想调用带或不带参数的python代码,那并不是很难。如果您的参数是基元,那么它将变得更加容易。但是,如果您想让Java类在python中实现成员函数,这些成员函数会更改java对象的数据,那么这并不是那么容易或直接的。

其次,我们在谈论cpython还是jython做?我会说cpython是它的所在!我主张这就是为什么python如此强大的原因!但是,在需要时具有如此高的抽象度却可以访问c,c ++。想象一下您是否可以在Java中使用它。这个问题甚至都不值得问jython是否还可以,因为这样很容易。

因此,我使用以下方法,并从容易到困难列出了它们:

Java到Jython

优点:轻而易举。实际引用Java对象

缺点:没有CPython,非常慢!

来自Java的Jython非常简单,如果确实够了,那就太好了。但是它非常慢并且没有cpython!没有cpython值得生活,我不这么认为!您可以轻松地让python代码为java对象实现成员函数。

通过Pyro从Java到Jython到CPython

Pyro是python的远程对象模块。您在cpython解释器上有一些对象,您可以向其发送通过序列化传输的对象,也可以通过此方法返回对象。请注意,如果您从jython发送一个序列化的python对象,然后调用某些函数来更改其成员中的数据,那么您将在java中看不到这些更改。您只需要记住从pyro发送回想要的数据。我相信这是进入cpython的最简单方法!您不需要任何jni或jna或swig或…。您不需要了解任何c或c ++。酷吧?

优点:访问cpython,不像以下方法那样困难

缺点:无法直接从python更改java对象的成员数据。有点间接,(jython是中间人)。

通过JNI / JNA / SWIG将Java转换为C / C ++,通过嵌入式解释器转换为Python(也许使用BOOST库?)

OMG这种方法不适合胆小的人。我可以告诉您,用一种体面的方法来实现这一目标已经花了我很长时间。您要执行此操作的主要原因是,您可以运行cpython代码,以完全控制您的java对象。在决定尝试使用python(就像一匹马)为java(像黑猩猩)做面包之前,需要考虑一些主要的主要事情。首先,如果您崩溃的解释器为您的程序点亮了!而且不要让我开始讨论并发问题!另外,还有锅炉分配器,我相信我已经找到了使该锅炉最小化的最佳配置,但仍然是分配器!那么该怎么做:考虑一下C ++是您的中间人,您的对象实际上就是c ++对象!很好,您现在就知道。只需编写您的对象,就好像您的程序在cpp中而不是java中一样,您想从两个世界访问的数据。然后,您可以使用名为swig(http://www.swig.org/Doc1.3/Java.html),以使Java可以访问此文件并编译一个dll,您可以在java中调用System.load(此处为dll名称)。首先使此工作正常,然后继续进行困难的工作!要使用python,您需要嵌入一个解释器。首先,我建议您编写一些hello解释程序或本教程 python嵌入C / C中。一旦完成这项工作,就该让马和Monkey跳舞了!您可以通过[boost] [3]将c ++对象发送给python。我知道我没有给你鱼,只是告诉你在哪里可以找到鱼。编译时需要注意的一些指针。

编译boost时,您将需要编译一个共享库。并且您需要包括并链接到jdk中所需的内容,即jawt.lib,jvm.lib(启动应用程序时,您的路径中还将需要客户端jvm.dll)以及python27.lib或以及boost_python-vc100-mt-1_55.lib。然后包括Python / include,jdk / include,boost,并且仅使用共享库(dll),否则boost有眼泪。是的,我知道。有很多方法可以解决此问题。因此,请确保您一步一步地完成每件事。然后将它们放在一起。

Hey I thought I would enter my answer to this even though its late. I think there are some important things to consider first with how strong you wish to have the linking between java and python.

Firstly Do you only want to call functions or do you actually want python code to change the data in your java objects? This is very important. If you only want to call some python code with or without arguments, then that is not very difficult. If your arguments are primitives it makes it even more easy. However if you want to have java class implement member functions in python, which change the data of the java object, then this is not so easy or straight forward.

Secondly are we talking cpython or will jython do? I would say cpython is where its at! I would advocate this is why python is so kool! Having such high abstractions however access to c,c++ when needed. Imagine if you could have that in java. This question is not even worth asking if jython is ok because then it is easy anyway.

So I have played with the following methods, and listed them from easy to difficult:

Java to Jython

Advantages: Trivially easy. Have actual references to java objects

Disadvantages: No CPython, Extremely Slow!

Jython from java is so easy, and if this is really enough then great. However it is very slow and no cpython! Is life worth living without cpython I don’t think so! You can easily have python code implementing your member functions for you java objects.

Java to Jython to CPython via Pyro

Pyro is the remote object module for python. You have some object on a cpython interpreter, and you can send it objects which are transferred via serialization and it can also return objects via this method. Note that if you send a serialized python object from jython and then call some functions which change the data in its members, then you will not see those changes in java. You just need to remember to send back the data which you want from pyro. This I believe is the easiest way to get to cpython! You do not need any jni or jna or swig or …. You don’t need to know any c, or c++. kool huh?

Advantages: Access to cpython, not as difficult as following methods

Disadvantages: Cannot change the member data of java objects directly from python. Is somewhat indirect, (jython is middle man).

Java to C/C++ via JNI/JNA/SWIG to Python via Embedded interpreter (maybe using BOOST Libraries?)

OMG this method is not for the faint of heart. And I can tell you it has taken me very long to achieve this in with a decent method. Main reason you would want to do this is so that you can run cpython code which as full rein over you java object. There are major major things to consider before deciding to try and bread java (which is like a chimp) with python (which is like a horse). Firstly if you crash the interpreter that’s lights out for you program! And don’t get me started on concurrency issues! In addition, there is allot allot of boiler, I believe I have found the best configuration to minimize this boiler but still it is allot! So how to go about this: Consider that C++ is your middle man, your objects are actually c++ objects! Good that you know that now. Just write your object as if your program as in cpp not java, with the data you want to access from both worlds. Then you can use the wrapper generator called swig (http://www.swig.org/Doc1.3/Java.html) to make this accessible to java and compile a dll which you call System.load(dll name here) in java. Get this working first, then move on to the hard part! To get to python you need to embed an interpreter. Firstly I suggest doing some hello interpreter programs or this tutorial Embedding python in C/C. Once you have that working, its time to make the horse and the monkey dance! You can send you c++ object to python via [boost][3] . I know I have not given you the fish, merely told you where to find the fish. Some pointers to note for this when compiling.

When you compile boost you will need to compile a shared library. And you need to include and link to the stuff you need from jdk, ie jawt.lib, jvm.lib, (you will also need the client jvm.dll in your path when launching the application) As well as the python27.lib or whatever and the boost_python-vc100-mt-1_55.lib. Then include Python/include, jdk/include, boost and only use shared libraries (dlls) otherwise boost has a teary. And yeah full on I know. There are so many ways in which this can go sour. So make sure you get each thing done block by block. Then put them together.


回答 2

在Java中包含python代码并不明智。用flask或其他Web框架包装您的python代码,使其成为微服务。使您的Java程序能够调用此微服务(例如,通过REST)。

相信我,这很简单,可以为您节省很多问题。而且代码是松散耦合的,因此它们是可伸缩的。

于2020年3月24日更新:根据@stx的评论,上述方法不适用于客户端和服务器之间的海量数据传输。这是我推荐的另一种方法:使用Rust连接Python和Java(也可以使用C / C ++)。 https://medium.com/@shmulikamar/https-medium-com-shmulikamar-connecting-python-and-java-with-rust-11c256a1dfb0

It’s not smart to have python code inside java. Wrap your python code with flask or other web framework to make it as a microservice. Make your java program able to call this microservice (e.g. via REST).

Beleive me, this is much simple and will save you tons of issues. And the codes are loosely coupled so they are scalable.

Updated on Mar 24th 2020: According to @stx’s comment, the above approach is not suitable for massive data transfer between client and server. Here is another approach I recommended: Connecting Python and Java with Rust(C/C++ also ok). https://medium.com/@shmulikamar/https-medium-com-shmulikamar-connecting-python-and-java-with-rust-11c256a1dfb0


回答 3

有几个答案提到您可以使用JNI或JNA来访问cpython,但我不建议您从头开始,因为已经有了用于从java访问cpython的开源库。例如:

Several of the answers mention that you can use JNI or JNA to access cpython but I would not recommend starting from scratch because there are already open source libraries for accessing cpython from java. For example:


回答 4

这里是一个库,可让您一次编写python脚本并确定在运行时使用哪种集成方法(Jython,CPython / PyPy(通过Jep和Py4j)):

https://github.com/subes/invesdwin-context-python

由于每种方法都有其自身的优点/缺点,如链接中所述。

Here a library that lets you write your python scripts once and decide which integration method (Jython, CPython/PyPy via Jep and Py4j) to use at runtime:

https://github.com/subes/invesdwin-context-python

Since each method has its own benefits/drawbacks as explained in the link.


回答 5

这取决于您对python函数的含义是什么?如果它们是用cpython编写的,则不能直接调用它们,则必须使用JNI,但是如果它们是用Jython编写的可以轻松地从Java调用它们,因为jython最终会生成Java字节码。

现在,当我说用cpython或jython编写时,这没有多大意义,因为python是python,并且除非您使用依赖于cpython或java的特定库,否则大多数代码都可以在两种实现上运行。

请参阅此处如何在Java中使用Python解释器。

It depends on what do you mean by python functions? if they were written in cpython you can not directly call them you will have to use JNI, but if they were written in Jython you can easily call them from java, as jython ultimately generates java byte code.

Now when I say written in cpython or jython it doesn’t make much sense because python is python and most code will run on both implementations unless you are using specific libraries which relies on cpython or java.

see here how to use Python interpreter in Java.


回答 6

根据您的要求,诸如XML-RPC之类的选项可能会很有用,它可以用于虚拟地以任何支持协议的语言远程调用函数。

Depending on your requirements, options like XML-RPC could be useful, which can be used to remotely call functions virtually in any language supporting the protocol.


回答 7

GraalVM是一个不错的选择。我已经完成了与GraalVM的Java + Javascript组合用于微服务设计(具有Javascript反射功能的Java)。他们最近增加了对python的支持,我想尝试一下,尤其是多年来这些社区的规模。

GraalVM is a good choice. I’ve done Java+Javascript combination with GraalVM for microservice design (Java with Javascript reflection). They recently added support for python, I’d give it a try especially with how big its community has grown over the years.


回答 8

您可以使用Java Native Interface从Java调用任何语言

You can call any language from java using Java Native Interface


回答 9

Jython有一些限制:

有许多差异。首先,Jython程序不能使用用C编写的CPython扩展模块。这些模块通常具有扩展名为.so,.pyd或.dll的文件。如果要使用这样的模块,则应寻找用纯Python或Java编写的等效模块。尽管在技术上支持此类扩展是可行的-IronPython这样做-在Jython中尚无计划这样做。

使用Jython将我的Python脚本作为JAR文件分发吗?

您只需使用Runtime或ProcessBuilder从Java调用python脚本(或bash或Perl脚本),然后将输出传递回Java:

在Java中运行bash shell脚本

在Java中运行命令行

java runtime.getruntime()从执行命令行程序获取输出

Jython has some limitations:

There are a number of differences. First, Jython programs cannot use CPython extension modules written in C. These modules usually have files with the extension .so, .pyd or .dll. If you want to use such a module, you should look for an equivalent written in pure Python or Java. Although it is technically feasible to support such extensions – IronPython does so – there are no plans to do so in Jython.

Distributing my Python scripts as JAR files with Jython?

you can simply call python scripts (or bash or Perl scripts) from Java using Runtime or ProcessBuilder and pass output back to Java:

Running a bash shell script in java

Running Command Line in Java

java runtime.getruntime() getting output from executing a command line program


回答 10

这样可以很好地概述当前的选项。其中一些在其他答案中被命名。在他们决定实现Python 3.x之前,Jython不可用,并且许多其他项目都来自python方面并希望访问java。但是,还有一些选项可以命名尚未命名的名称:gRPC

This gives a pretty good overview over the current options. Some of which are named in other answers. Jython is not usable until they decide to implement Python 3.x and many of the other projects are coming form the python side and want to access java. But there are a few options still, to name something which has not been named yet: gRPC


“ is None”和“ == None”有什么区别?

问题:“ is None”和“ == None”有什么区别?

我最近遇到了这种语法,我不知道有什么区别。

如果有人可以告诉我与众不同,我将不胜感激。

I recently came across this syntax, I am unaware of the difference.

I would appreciate it if someone could tell me the difference.


回答 0

答案在这里解释。

报价:

一个类可以自由选择以任何方式实现比较,并且可以选择与None进行比较意味着某种意义(这实际上是有道理的;如果有人告诉您从头开始实现None对象,那么您将如何获得它来比较True?反对自己?)。

实际上,由于自定义比较运算符很少见,因此差异不大。但是您应该使用is None一般规则。

The answer is explained here.

To quote:

A class is free to implement comparison any way it chooses, and it can choose to make comparison against None mean something (which actually makes sense; if someone told you to implement the None object from scratch, how else would you get it to compare True against itself?).

Practically-speaking, there is not much difference since custom comparison operators are rare. But you should use is None as a general rule.


回答 1

class Foo:
    def __eq__(self,other):
        return True
foo=Foo()

print(foo==None)
# True

print(foo is None)
# False
class Foo:
    def __eq__(self,other):
        return True
foo=Foo()

print(foo==None)
# True

print(foo is None)
# False

回答 2

在这种情况下,它们是相同的。None是单例对象(只有一个存在None)。

is 检查对象是否是同一对象,而==只是检查它们是否等效。

例如:

p = [1]
q = [1]
p is q # False because they are not the same actual object
p == q # True because they are equivalent

但是由于只有一个None,它们将始终相同,is并将返回True。

p = None
q = None
p is q # True because they are both pointing to the same "None"

In this case, they are the same. None is a singleton object (there only ever exists one None).

is checks to see if the object is the same object, while == just checks if they are equivalent.

For example:

p = [1]
q = [1]
p is q # False because they are not the same actual object
p == q # True because they are equivalent

But since there is only one None, they will always be the same, and is will return True.

p = None
q = None
p is q # True because they are both pointing to the same "None"

回答 3

如果您使用numpy,

if np.zeros(3)==None: pass

numpy进行元素比较时会给你错误

If you use numpy,

if np.zeros(3)==None: pass

will give you error when numpy does elementwise comparison


回答 4

这取决于您要与“无”进行比较。一些类具有自定义比较方法,这些方法与== None区别对待is None

特别是的输出a == None 甚至不必是布尔值!-错误的常见原因。

对于特定示例,请使用numpy数组,其中==逐元素实现比较:

import numpy as np
a = np.zeros(3) # now a is array([0., 0., 0.])
a == None #compares elementwise, outputs array([False, False, False]), i.e. not boolean!!!
a is None #compares object to object, outputs False

It depends on what you are comparing to None. Some classes have custom comparison methods that treat == None differently from is None.

In particular the output of a == None does not even have to be boolean !! – a frequent cause of bugs.

For a specific example take a numpy array where the == comparison is implemented elementwise:

import numpy as np
a = np.zeros(3) # now a is array([0., 0., 0.])
a == None #compares elementwise, outputs array([False, False, False]), i.e. not boolean!!!
a is None #compares object to object, outputs False

有没有办法在Android上运行Python?

问题:有没有办法在Android上运行Python?

我们正在开发S60版本,该平台具有不错的Python API。

但是,关于Android上的Python尚无官方资料,但是由于Jython存在,有没有办法让蛇和机器人一起工作?

We are working on an S60 version and this platform has a nice Python API..

However, there is nothing official about Python on Android, but since Jython exists, is there a way to let the snake and the robot work together??


回答 0

一种方法是使用Kivy

开源Python库,用于快速开发利用创新用户界面的应用程序,例如多点触控应用程序。

Kivy可在Linux,Windows,OS X,Android和iOS上运行。您可以在所有受支持的平台上运行相同的[python]代码。

Kivy Showcase应用程序

One way is to use Kivy:

Open source Python library for rapid development of applications that make use of innovative user interfaces, such as multi-touch apps.

Kivy runs on Linux, Windows, OS X, Android and iOS. You can run the same [python] code on all supported platforms.

Kivy Showcase app


回答 1

还有一个新的Android脚本环境(ASE / SL4A)项目。它看起来很棒,并且与本机Android组件集成在一起。

注意:不再处于“主动开发”之下,但是可能有一些分支。

There is also the new Android Scripting Environment (ASE/SL4A) project. It looks awesome, and it has some integration with native Android components.

Note: no longer under “active development”, but some forks may be.


回答 2

是! :Android脚本环境

一个例子通过马特·卡茨通过SL4A – “这是写在Python代码半年线条码扫描器:

import android
droid = android.Android()
code = droid.scanBarcode()
isbn = int(code['result']['SCAN_RESULT'])
url = "http://books.google.com?q=%d" % isbn
droid.startActivity('android.intent.action.VIEW', url)

Yes! : Android Scripting Environment

An example via Matt Cutts via SL4A — “here’s a barcode scanner written in six lines of Python code:

import android
droid = android.Android()
code = droid.scanBarcode()
isbn = int(code['result']['SCAN_RESULT'])
url = "http://books.google.com?q=%d" % isbn
droid.startActivity('android.intent.action.VIEW', url)

回答 3

适用于Android的Pygame子集

Pygame是适用于Python(在桌面上)的2D游戏引擎,在新程序员中很流行。AndroidPygame子集将自己描述为…

…将Pygame功能的子集移植到Android平台。该项目的目标是允许创建特定于Android的游戏,并简化游戏从类似PC的平台到Android的移植。

示例包括打包为APK的完整游戏,这很有趣。

Pygame Subset for Android

Pygame is a 2D game engine for Python (on desktop) that is popular with new programmers. The Pygame Subset for Android describes itself as…

…a port of a subset of Pygame functionality to the Android platform. The goal of the project is to allow the creation of Android-specific games, and to ease the porting of games from PC-like platforms to Android.

The examples include a complete game packaged as an APK, which is pretty interesting.


回答 4

交叉编译和Ignifuga

我的博客上有说明和补丁用于Android的Python 2.7.2交叉编译的。

我还开源了我的2D游戏引擎Ignifuga。它基于Python / SDL,并且可以为Android交叉编译。即使您不将它用于游戏,您也可能会从代码或构建器实用程序(以Tim 命名的Schafer ……知道谁)中得到有用的想法。

Cross-Compilation & Ignifuga

My blog has instructions and a patch for cross compiling Python 2.7.2 for Android.

I’ve also open sourced Ignifuga, my 2D Game Engine. It’s Python/SDL based, and it cross compiles for Android. Even if you don’t use it for games, you might get useful ideas from the code or builder utility (named Schafer, after Tim… you know who).


回答 5

Android脚本层

SL4A做您想要的。您可以轻松地将其从其站点直接安装到设备上,而无需root用户。

它支持多种语言。Python是最成熟的。默认情况下,它使用Python 2.6,但是您可以使用3.2端口。我已经将该端口用于Galaxy S2上的所有东西,并且工作正常。

API

SL4A android为每种支持的语言提供了其库的端口。该库通过单个Android对象提供了与基础Android API的接口。

from android import Android

droid = Android()
droid.ttsSpeak('hello world') # example using the text to speech facade

每种语言都有几乎相同的API。您甚至可以在webview中使用JavaScript API。

let droid = new Android();
droid.ttsSpeak("hello from js");

使用者介面

对于用户界面,您有三个选择:

  • 您可以通过API轻松使用通用的本机对话和菜单。这对于确认对话和其他基本用户输入很有用。
  • 您还可以从Python脚本中打开Web视图,然后将HTML5用作用户界面。当您使用Python中的Web视图时,可以在Web视图和生成它的Python进程之间来回传递消息。用户界面不会是本机的,但仍然是一个不错的选择。
  • 一些对Android本机用户界面的支持,但是我不确定它的运行情况如何;我只是从未使用过它。

您可以混合使用选项,因此您可以在主界面上拥有一个Web视图,并且仍然使用本机对话。

QPython的

有一个名为QPython的第三方项目。它建立在SL4A之上,并抛出了其他有用的东西。

QPython为您提供了一个更好的UI来管理安装,并包括一个小的触摸屏代码编辑器,一个Python Shell和一个用于程序包管理的PIP Shell。它们还具有Python 3端口。两种版本均可从Play商店免费获得。QPython还在Android项目(包括Kivy)上捆绑了来自大量Python的库,因此它不仅仅是SL4A。

请注意,QPython仍在开发SL4A的分支(尽管,说实话,没有太多)。SL4A的主要项目本身已经死了。

有用的链接

Scripting Layer for Android

SL4A does what you want. You can easily install it directly onto your device from their site, and do not need root.

It supports a range of languages. Python is the most mature. By default, it uses Python 2.6, but there is a 3.2 port you can use instead. I have used that port for all kinds of things on a Galaxy S2 and it worked fine.

API

SL4A provides a port of their android library for each supported language. The library provides an interface to the underlying Android API through a single Android object.

from android import Android

droid = Android()
droid.ttsSpeak('hello world') # example using the text to speech facade

Each language has pretty much the same API. You can even use the JavaScript API inside webviews.

let droid = new Android();
droid.ttsSpeak("hello from js");

User Interfaces

For user interfaces, you have three options:

  • You can easily use the generic, native dialogues and menus through the API. This is good for confirmation dialogues and other basic user inputs.
  • You can also open a webview from inside a Python script, then use HTML5 for the user interface. When you use webviews from Python, you can pass messages back and forth, between the webview and the Python process that spawned it. The UI will not be native, but it is still a good option to have.
  • There is some support for native Android user interfaces, but I am not sure how well it works; I just haven’t ever used it.

You can mix options, so you can have a webview for the main interface, and still use native dialogues.

QPython

There is a third party project named QPython. It builds on SL4A, and throws in some other useful stuff.

QPython gives you a nicer UI to manage your installation, and includes a little, touchscreen code editor, a Python shell, and a PIP shell for package management. They also have a Python 3 port. Both versions are available from the Play Store, free of charge. QPython also bundles libraries from a bunch of Python on Android projects, including Kivy, so it is not just SL4A.

Note that QPython still develop their fork of SL4A (though, not much to be honest). The main SL4A project itself is pretty much dead.

Useful Links


回答 6

作为一个Python的爱好者和Android程序员,我很伤心地说,这是不是一个很好的路要走。有两个问题:

一个问题是,Android开发工具不只是一种编程语言。许多Android图形涉及XML文件来配置显示,类似于HTML。内置的Java对象与此XML布局集成在一起,比编写代码从逻辑到位图要容易得多。

另一个问题是G1(以及不久的将来可能还有其他Android设备)的运行速度并不快。200 MHz处理器和RAM非常有限。即使是在Java中,如果要使应用程序完全流畅,也必须进行大量重写以避免创建更多对象。在移动设备上运行一段时间后,Python将变得太慢。

As a Python lover and Android programmer, I’m sad to say this is not a good way to go. There are two problems:

One problem is that there is a lot more than just a programming language to the Android development tools. A lot of the Android graphics involve XML files to configure the display, similar to HTML. The built-in java objects are integrated with this XML layout, and it’s a lot easier than writing your code to go from logic to bitmap.

The other problem is that the G1 (and probably other Android devices for the near future) are not that fast. 200 MHz processors and RAM is very limited. Even in Java, you have to do a decent amount of rewriting-to-avoid-more-object-creation if you want to make your app perfectly smooth. Python is going to be too slow for a while still on mobile devices.


回答 7

基维

我想补充一下@JohnMudd关于Kivy的文章。自从他描述这种情况以来已经有好几年了,而Kivy有了长足的发展。

我认为,Kivy的最大卖点是其跨平台兼容性。您可以使用任何桌面环境(Windows / * nix等)对所有内容进行编码和测试,然后将您的应用打包到一系列不同的平台上,包括Android,iOS,MacOS和Windows(尽管应用通常缺乏本机外观)。

使用Kivy自己的KV语言,您可以轻松编码和构建GUI界面(就像Java XML一样,但不是TextView等,KV拥有自己的ui.widgets的类似翻译功能),我认为这很容易采用。

当前,最推荐使用Buildozerpython-for-android工具来构建和打包应用程序。我对它们都进行了尝试,可以肯定地说,它们使使用Python构建Android应用程序变得轻而易举。他们的指南也有据可查。

iOS是Kivy的另一个大卖点。您可以使用相同的代码库,通过kivy-ios Homebrew工具进行少量更改,尽管构建需要Xcode,但在其设备上运行之前(AFAIK,Xcode中的iOS Simulator当前不适用于x86体系结构构建) 。为了成功构建,还必须手动在Xcode中解决一些依赖项问题,并加以解决,但这并不太容易解决,并且Kivy Google Group的人员也非常有帮助。

综上所述,具有良好Python知识的用户应该不会有任何问题,很快就能掌握基础知识。

如果将Kivy用于更重要的项目,则可能会发现现有模块不令人满意。虽然有一些可行的解决方案。通过适用于Android的pyjniuspyobjus,用户现在可以访问Java / Objective-C类来控制某些本机API。

Kivy

I wanted to add to what @JohnMudd has written about Kivy. It has been years since the situation he described, and Kivy has evolved substantially.

The biggest selling point of Kivy, in my opinion, is its cross-platform compatibility. You can code and test everything using any desktop environment (Windows/*nix etc.), then package your app for a range of different platforms, including Android, iOS, MacOS and Windows (though apps often lack the native look and feel).

With Kivy’s own KV language, you can code and build the GUI interface easily (it’s just like Java XML, but rather than TextView etc., KV has its own ui.widgets for a similar translation), which is in my opinion quite easy to adopt.

Currently Buildozer and python-for-android are the most recommended tools to build and package your apps. I have tried them both and can firmly say that they make building Android apps with Python a breeze. Their guides are well documented too.

iOS is another big selling point of Kivy. You can use the same code base with few changes required via kivy-ios Homebrew tools, although Xcode is required for the build, before running on their devices (AFAIK the iOS Simulator in Xcode currently doesn’t work for the x86-architecture build). There are also some dependency issues which must be manually compiled and fiddled around with in Xcode to have a successful build, but they wouldn’t be too difficult to resolve and people in Kivy Google Group are really helpful too.

With all that being said, users with good Python knowledge should have no problem picking up the basics quickly.

If you are using Kivy for more serious projects, you may find existing modules unsatisfactory. There are some workable solutions though. With the (work in progress) pyjnius for Android, and pyobjus, users can now access Java/Objective-C classes to control some of the native APIs.


回答 8

Termux

您可以使用Termux应用程序(该程序为Android提供POSIX环境)来安装Python。

请注意,这apt install python将在Termux上安装Python3。对于Python2,您需要使用apt install python2

Termux

You can use the Termux app, which provides a POSIX environment for Android, to install Python.

Note that apt install python will install Python3 on Termux. For Python2, you need to use apt install python2.


回答 9

目前还没有,您很幸运能让Jython很快上班。如果您打算现在开始开发,那么最好还是坚持使用Java。

Not at the moment and you would be lucky to get Jython to work soon. If you’re planning to start your development now you would be better off with just sticking to Java for now on.


回答 10

使用SL4A(在其他答案中已经提到过),您可以运行成熟的web2py实例(其他python web框架也可能是候选对象)。SL4A不允许您执行本机UI组件(按钮,滚动条等),但它确实支持WebViews。WebView基本上只不过是指向固定地址的带状结构的Web浏览器。我相信本机Gmail应用程序使用WebView而非常规的窗口小部件路线。

这条路线将具有一些有趣的功能:

  • 对于大多数python网络框架,您实际上可以在不使用android设备或android模拟器的情况下进行开发和测试。
  • 无论您最终为手机编写的任何Python代码,也都可以进行很小的修改(如果有的话)放在公共Web服务器上。
  • 您可以利用那里所有疯狂的网络内容:查询,HTML5,CSS3等。

Using SL4A (which has already been mentioned by itself in other answers) you can run a full-blown web2py instance (other python web frameworks are likely candidates as well). SL4A doesn’t allow you to do native UI components (buttons, scroll bars, and the like), but it does support WebViews. A WebView is basically nothing more than a striped down web browser pointed at a fixed address. I believe the native Gmail app uses a WebView instead of going the regular widget route.

This route would have some interesting features:

  • In the case of most python web frameworks, you could actually develop and test without using an android device or android emulator.
  • Whatever Python code you end up writing for the phone could also be put on a public webserver with very little (if any) modification.
  • You could take advantage of all of the crazy web stuff out there: query, HTML5, CSS3, etc.

回答 11

QPython的

我使用QPython应用程序。它是免费的,包括代码编辑器,交互式解释器和程序包管理器,可让您直接在设备上创建和执行Python程序。

QPython

I use the QPython app. It’s free and includes a code editor, an interactive interpreter and a package manager, allowing you to create and execute Python programs directly on your device.


回答 12

适用于AndroidPython站点:

适用于Android的Python是一个用于创建自己的Python发行版(包括所需模块)并创建包含python,lib和应用程序的apk的项目。

From the Python for android site:

Python for android is a project to create your own Python distribution including the modules you want, and create an apk including python, libs, and your application.


回答 13

Chaquopy

Chaquopy是Android Studio基于Gradle的构建系统的插件。它着重于与标准Android开发工具的紧密集成

  • 它提供了完整的API,可以从Python调用Java从Java调用Python,从而允许开发人员使用最适合其应用程序每个组件的语言。

  • 它可以自动下载PyPI软件包并将其构建到应用程序中,包括选定的本机软件包,例如NumPy。

  • 它使您能够从Python完全访问所有Android API,包括本机用户界面工具包(纯Python活动示例)。

这是一种商业产品,但可免费用于开放源代码,并且将始终保持这种状态。

(我是这个产品的创造者。)

Chaquopy

Chaquopy is a plugin for Android Studio’s Gradle-based build system. It focuses on close integration with the standard Android development tools.

  • It provides complete APIs to call Java from Python or Python from Java, allowing the developer to use whichever language is best for each component of their app.

  • It can automatically download PyPI packages and build them into an app, including selected native packages such as NumPy.

  • It enables full access to all Android APIs from Python, including the native user interface toolkit (example pure-Python activity).

This is a commercial product, but it’s free for open-source use and will always remain that way.

(I am the creator of this product.)


回答 14

另一尝试:https : //code.google.com/p/android-python27/

这直接将Python解释器嵌入到您的应用apk中。

Yet another attempt: https://code.google.com/p/android-python27/

This one embed directly the Python interpretter in your app apk.


回答 15

是python官方网站上列出的一些工具


Playstore中有一个名为QPython3的应用程序,可用于编辑和运行python脚本。

Playstore连结


另一个名为Termux的应用程序,您可以在其中使用命令安装python

pkg install python

Playstore连结


如果您想开发应用程序,则可以使用Python Android脚本层(SL4A

The Scripting Layer for Android, SL4A, is an open source application that allows programs written in a range of interpreted languages to run on Android. It also provides a high level API that allows these programs to interact with the Android device, making it easy to do stuff like accessing sensor data, sending an SMS, rendering user interfaces and so on.


您还可以检查适用于Android的PySide,它实际上是Qt 4的Python绑定。


有一个称为PyMob的平台,其中的应用程序可以完全用Python编写,并且编译器工具流(PyMob)可以将它们转换为适用于各种平台的本机源代码。


同时检查python-for-android

python-for-android is an open source build tool to let you package Python code into standalone android APKs. These can be passed around, installed, or uploaded to marketplaces such as the Play Store just like any other Android app. This tool was originally developed for the Kivy cross-platform graphical framework, but now supports multiple bootstraps and can be easily extended to package other types of Python apps for Android.


试用适用 于Android的Chaquopy A Python SDK


Anddd … BeeWare

BeeWare allows you to write your app in Python and release it on multiple platforms. No need to rewrite the app in multiple programming languages. It means no issues with build tools, environments, compatibility, etc.

Here are some tools listed in official python website


There is an app called QPython3 in playstore which can be used for both editing and running python script.

Playstore link


Another app called Termux in which you can install python using command

pkg install python

Playstore Link


If you want develop apps , there is Python Android Scripting Layer (SL4A) .

The Scripting Layer for Android, SL4A, is an open source application that allows programs written in a range of interpreted languages to run on Android. It also provides a high level API that allows these programs to interact with the Android device, making it easy to do stuff like accessing sensor data, sending an SMS, rendering user interfaces and so on.


You can also check PySide for Android, which is actually Python bindings for the Qt 4.


There’s a platform called PyMob where apps can be written purely in Python and the compiler tool-flow (PyMob) converts them in native source codes for various platforms.


Also check python-for-android

python-for-android is an open source build tool to let you package Python code into standalone android APKs. These can be passed around, installed, or uploaded to marketplaces such as the Play Store just like any other Android app. This tool was originally developed for the Kivy cross-platform graphical framework, but now supports multiple bootstraps and can be easily extended to package other types of Python apps for Android.


Try Chaquopy A Python SDK for Android


Anddd… BeeWare

BeeWare allows you to write your app in Python and release it on multiple platforms. No need to rewrite the app in multiple programming languages. It means no issues with build tools, environments, compatibility, etc.


回答 16

您可以使用sl4a运行Python代码。sl4a支持Python,PerlJRubyLua,BeanShell,JavaScript,Tcl和Shell脚本。

您可以学习sl4a Python示例

You can run your Python code using sl4a. sl4a supports Python, Perl, JRuby, Lua, BeanShell, JavaScript, Tcl, and shell script.

You can learn sl4a Python Examples.


回答 17

您可以使用QPython

它具有Python控制台,编辑器以及程序包管理/安装程序

http://qpython.com/

这是一个具有Python 2和Python 3实现的开源项目。您可以直接从github下载源代码和Android .apk文件。

QPython 2:https//github.com/qpython-android/qpython/releases

QPython 3:https//github.com/qpython-android/qpython3/releases

You can use QPython:

It has a Python Console, Editor, as well as Package Management / Installers

http://qpython.com/

It’s an open source project with both Python 2 and Python 3 implementations. You can download the source and the Android .apk files directly from github.

QPython 2: https://github.com/qpython-android/qpython/releases

QPython 3: https://github.com/qpython-android/qpython3/releases


回答 18

如果您正在寻找3.4.2或3.5.1,则另一个选择是GitHub上的此存档。

Python3-Android 3.4.2 Python3-Android 3.5.1

目前,它支持Python 3.4.2或3.5.1以及NDK的10d版本。它还可以支持3.3和9c,11c和12

只需下载,运行make并获得.so或.a即可,这非常不错。

我目前使用它在Android设备上运行原始Python。通过对构建文件进行一些修改,您还可以将x86和armeabi制作为64位

Another option if you are looking for 3.4.2 or 3.5.1 is this archive on GitHub.

Python3-Android 3.4.2 or Python3-Android 3.5.1

It currently supports Python 3.4.2 or 3.5.1 and the 10d version of the NDK. It can also support 3.3 and 9c, 11c and 12

It’s nice in that you simply download it, run make and you get the .so or the .a

I currently use this to run raw Python on android devices. With a couple modifications to the build files you can also make x86 and armeabi 64 bit


回答 19

没有在此处看到此消息,但是由于Necessitas,Qt可以在Android上运行,因此您可以使用Pyside和Qt来做到这一点。

目前看来似乎很仓促,但最终可能是一条可行的路线…

http://qt-project.org/wiki/PySide_for_Android_guide

Didn’t see this posted here, but you can do it with Pyside and Qt now that Qt works on Android thanks to Necessitas.

It seems like quite a kludge at the moment but could be a viable route eventually…

http://qt-project.org/wiki/PySide_for_Android_guide


回答 20

pyqtdeploy似乎是一种选择,引用该文档是:

该工具与Qt随附的其他工具结合使用,可以部署用Python v2.7或Python v3.3或更高版本编写的PyQt4和PyQt5应用程序。它支持部署到桌面平台(Linux,Windows和OS X)以及移动平台(iOS和Android)。

根据通过pyqtdeploy和Qt5PyQt5应用程序部署到Android的说法,该应用程序是积极开发的,尽管很难找到有效的Android应用程序示例或关于如何将所有必需的库交叉编译到Android的教程。请记住,这是一个有趣的项目!

One more option seems to be pyqtdeploy which citing the docs is:

a tool that, in conjunction with other tools provided with Qt, enables the deployment of PyQt4 and PyQt5 applications written with Python v2.7 or Python v3.3 or later. It supports deployment to desktop platforms (Linux, Windows and OS X) and to mobile platforms (iOS and Android).

According to Deploying PyQt5 application to Android via pyqtdeploy and Qt5 it is actively developed, although it is difficult to find examples of working Android apps or tutorial on how to cross-compile all the required libraries to Android. It is an interesting project to keep in mind though!


回答 21

看一下BeeWare。在回答这个问题时,它仍处于早期开发中。目的是能够使用Python为所有受支持的操作系统(包括Android)创建本机应用程序。

Take a look at BeeWare. At the moment of answering this question it is still in early development. It’s aim is to be able to create native apps with Python for all supported operating systems, including Android.


回答 22

看看enaml-native,它采用了react-native概念并将其应用于python。

它允许用户使用本机Android小部件来构建应用,并提供API以使用来自python的android和java库。

它还与android-studio集成,并共享了react的一些不错的开发功能,例如代码重载和远程调试。

Check out enaml-native which takes the react-native concept and applies it to python.

It lets users build apps with native Android widgets and provides APIs to use android and java libraries from python.

It also integrates with android-studio and shares a few of react’s nice dev features like code reloading and remote debugging.