欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-04-19 23:16:52
上篇讲到 pad 从pc接收文件的脚本 getfile1.py 这篇讲 android 手机从pc接收文件的脚本 getfile2.py , 这个比getfile1.py更好用....

上篇讲到 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( )