3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

adb経由でPCからAndroid上のPythonと対話する

Last updated at Posted at 2013-07-26

SL4Aでは、Android上でもPythonのREPLが使えます。ただ、せっかく目の前にPCがあるなら、キーボードとモニタでREPLできると何かと便利です。

SL4Aサービスを起動する

まずRPCサービスを起動します。アプリを操作する方法と、シェル
から起動する方法があります。

アプリから起動

SL4Aのアプリでインタプリタの一覧を開き、メニューから"Start Server"を選びます。

server.png

"Public"を選ぶと外部にポートが開き、"Private"では内部のみになります。

サーバが起動すると、RPC用のポートが開きます。通知バーに出る項目からポート番号を確認できます。

ポート番号は通常ランダムに決まりますが、アプリの設定項目にある"Server Port"でポートを固定できます。

シェルから起動

シェルで次のように am コマンドを使います。

$ am start \
 -a com.googlecode.android_scripting.action.LAUNCH_SERVER \
 -n com.googlecode.android_scripting/.activity.ScriptingLayerServiceLauncher

Server Portの設定は影響しませんが、インテントのパラメータ指定することができます。

$ am start \
 -a com.googlecode.android_scripting.action.LAUNCH_SERVER \
 -n com.googlecode.android_scripting/.activity.ScriptingLayerServiceLauncher \
 --ei com.googlecode.android_scripting.extra.USE_SERVICE_PORT 12345

標準ではプライベートとして開きますが、パラメータでパブリックにすることができます。

$ am start \
 -a com.googlecode.android_scripting.action.LAUNCH_SERVER \
 -n com.googlecode.android_scripting/.activity.ScriptingLayerServiceLauncher \
 --ez om.googlecode.android_scripting.extra.USE_PUBLIC_IP true

Pythonを起動する

次に、Pythonを起動します。

Android本体のPythonを使う方法と、PCのPythonを使う方法があります。

Android本体のPythonを使う

Pythonインタプリタ本体を直にadbシェル上で起動します。その際、AP_PORT環境変数に起動したサーバのポートを指定します。

# 環境設定は試行錯誤して通ったものなのでお使いの環境で動くかはわかりません
# 12345はRPCサーバのポート番号です
$ AP_PORT=12345 \
  LD_LIBRARY_PATH=/data/data/com.googlecode.pythonforandroid/files/python/lib:$LD_LIBRARY_PATH \
  PYTHONPATH=/sdcard/com.googlecode.pythonforandroid/extras/python \
  PYTHONHOME=/data/data/com.googlecode.pythonforandroid/files/python \
  /data/data/com.googlecode.pythonforandroid/files/python/bin/python

pythonが起動すればそのまま対話が可能です。

PCのPythonを使う

パソコン側のPythonからもポートがつながればRPCができます。python_extras.zipに入っているandroid.pyimportして使います。

サーバをPrivateで起動した場合は、adbのポートフォワードを使います。

$ adb forward tcp:12345 tcp:12345
$ AP_PORT=12345 python

サーバをPublicで起動した場合は、AP_HOST環境変数でAndroidのIPアドレスを指定します。

$ AP_HOST=192.168.1.123 AP_PORT=12345 python

いずれの場合もAP_PORT環境変数でRPCサーバのポート番号を指定します。環境変数の代わりに、droid = android.Android(('127.0.0.1', 12345)) のように引数でアドレスを指定することもできます。

うまくいけばSL4A本体と同様の機能が使えます。

>>> import android
>>> droid = android.Android()
>>> droid.makeToast("hello, world!")
Result(id=0, result=None, error=None)

(参考: Stack Overflow - Unable to connect to SL4A server)

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?