python for android : 手机从PC接收文件


上篇讲到 pad 从PC接收文件的脚本 getfile1.py

这篇讲 android 手机从PC接收文件的脚本 getfile2.py , 这个比getfile1.py更好用.

# -*- coding: utf8 -*-
import android
import sys, os, time
from socket import *

droid = android.Android()
def now(): return time.strftime('%Y-%m-%d %X',time.localtime())
if droid.checkWifiState().result == False:
    print ' check Wifi State '
    sys.exit(4)

base_dir = '/mnt/sdcard/sl4a/scripts/'
if not os.path.isdir(base_dir):
    print base_dir,'is not dir'
    sys.exit(4)

def show_dir(path=base_dir):
    """Shows the contents of a directory in a list view."""
    # The files & directories under "path".
    nodes = sorted(os.listdir(path))
    # Make a way to go up a level.
    if path != base_dir: nodes.insert(0, '..')
    droid.dialogCreateAlert(os.path.basename(path).title())
    droid.dialogSetItems(nodes)
    droid.dialogShow()

    # Get the selected file or directory.
    result = droid.dialogGetResponse().result
    droid.dialogDismiss()
    if 'item' not in result:
        return
    target = nodes[result['item']]
    target_path = os.path.join(path, target)
    if target == '..': target_path = os.path.dirname(path)
    
    if os.path.isdir(target_path):
        show_dir(target_path)
    elif os.path.splitext(target)[1].lower() == '.py':
        return target_path
    # inform the user.
    else:
        droid.makeToast('Only .py files are currently supported!')
        show_dir(path)


path = show_dir()
filename = droid.dialogGetInput(u"从PC接收文件",os.path.dirname(path),os.path.basename(path)).result
if filename is not None:
    path = os.path.dirname(path) +'/'+ filename
print path

bufsz = 1024
host = '192.168.0.103'
port = 55555

sock = socket(AF_INET, SOCK_STREAM)
sock.connect((host, port))
sock.send(filename + '\n')                 # send remote name with dir
file = open(path, 'wb')                 # create local file in cwd
while True:
    data = sock.recv(bufsz)                # get up to 1K at a time
    if not data: break                     # till closed on server side
    file.write(data)                       # store data in local file
file.close( )
sock.close( )
print 'Client get', filename, 'at', now( )


评论关闭