2007-4-20 10:35 vhly
Python for S60 手机端

功能强筋,
支持各种操作

本代码使用手机编写 请回复后复制,
以对作者支持。

author:vhly[FR]

[code]
# SYMBIANUID=0x01234560

#This Python Script is to edit any text and save any type
#
# Author:vhly[FR]
# Date:2007/03/24

import appuifw
import sys
import e32
import os
import sysinfo
from binascii import *
import imp
import marshal
import time
import struct

if e32.s60_version_info>=(3,0):
    PYTHON_PATH = '\\python'
    APPMGR_PATH = 'c:\\private\\F0201512'
    LIB_PATH = '\\sys\\bin'
    APPS_PATH = '\\sys\\bin'
else:
    PYTHON_PATH = '\\system\\apps\\python'
    APPMGR_PATH = '\\system\\apps\\appmgr'
    LIB_PATH = '\\system\\libs'
    APPS_PATH = '\\system\\apps'

PYTHON_EXTS = ['.py', '.pyc', '.pyo', '.pyd']
PYTHON_LIB_EXTS = ['.pyc', '.pyo', '.pyd']

def python_drive():
    if e32.s60_version_info>=(3,0):
        return "C:"
    for drive in [str(x) for x in e32.drive_list()]:
        if os.path.isfile(os.path.join(drive, PYTHON_PATH, 'python.app')):
            return drive
    raise AssertionError, "Python not found"

def standalone_install(filename):
    def reverse(L):
        L.reverse()
        return L
    def atoi(s):
        # Little-endian conversion from a 4-char string to an int.
        sum = 0L
        for x in reverse([x for x in s[0:4]]):
            sum = (sum << 8) + ord(x)
        return sum
    def itoa(x):
        # Little-endian conversion from an int to a 4-character string.
        L=[chr(x>>24), chr((x>>16)&0xff), chr((x>>8)&0xff), chr(x&0xff)]
        L.reverse()
        return ''.join(L)

    try:
        offset = int(file(os.path.join(python_drive(), APPMGR_PATH,
                                       'uid_offset_in_app')).read(), 16)
    except:
        offset = None

    app_rootname = os.path.splitext(os.path.split(filename)[1])[0]
    app_dir = os.path.join(python_drive(), APPS_PATH, app_rootname)                       

    #
    # read the UID from the script file
    #
    script = file(filename, 'r').read()
    uidpos = script.find('SYMBIANUID=')
    if uidpos == -1:
        uid_text = appuifw.query(u'Give UID', 'text', u'0xXXXXXXXX')
        if not uid_text == None:
            uid = int(uid_text, 16)
        else:
            appuifw.note(u"Installation cancelled", "info")
            return
    else:
        uidpos = uidpos+len('SYMBIANUID=')
        while uidpos+10 < len(script) and script[uidpos].isspace():
            uidpos = uidpos+1
        if uidpos == len(script):
            appuifw.note(u"UID not found", "error")
            return
        else:
            uid = int(script[uidpos:uidpos+10], 16)

    #
    # copy the script to application's directory as default.py
    #
    if not os.path.isdir(app_dir):
        os.mkdir(app_dir)
    e32.file_copy(unicode(os.path.join(app_dir, 'default.py')),
                  unicode(filename))

    #
    # copy the template .app file to application directory with proper name
    # and set the UID and checksum fields suitably
    #
    template_dotapp = file(os.path.join(python_drive(), APPMGR_PATH, 'pyapp_template.tmp'))
    dotapp_name = app_rootname + '.app'
    dotapp = file(os.path.join(app_dir, dotapp_name), 'w')
    appbuf = template_dotapp.read()
    csum = atoi(appbuf[24:28])
    crc1 = itoa(e32._uidcrc_app(uid))
    crc2 = itoa(( uid + csum ) & 0xffffffffL)
    if offset:
        temp = appbuf[0:8] + itoa(uid) + crc1 + appbuf[16:24] + crc2 +\
               appbuf[28:offset] + itoa(uid) + appbuf[(offset+4):]
    else:
        temp = appbuf[0:8] + itoa(uid) + crc1 + appbuf[16:24] + crc2 + appbuf[28:]
    dotapp.write(temp)

    #
    # copy the template .rsc file to application directory with proper name
    #
    rsc_name = app_rootname + '.rsc'
    e32.file_copy(unicode(os.path.join(app_dir, app_rootname + '.rsc')),
                  unicode(os.path.join(python_drive(), APPMGR_PATH, 'pyrsc_template.tmp')))
    return app_dir

# set the application screen normal
appuifw.app.screen='normal'

# create a text editor
mainEdit = appuifw.Text()

mainEdit.style=appuifw.STYLE_BOLD

#mainEdit.color=(255,0,0)

# get the app lock
app_lock = e32.Ao_lock()

# set the app screen in edit
appuifw.app.body = mainEdit

#default file path is e
target_file=u"e:\\"

def ex():
    sys.exit()
    app_lock.signal()

def readFile(filename):
        file = open(filename,'rb')
        text = file.read().decode('utf8')
        file.close()
        return text

def saveFile(filename,text):
        file = open(filename, 'wb')
        file.write(text)
        file.close()

def saveAsFile(filename, text):
        saveFile(filename,text)

def openFileMenu():
        global target_file
        filename = appuifw.query(u"Open File",'text',target_file)
        if not filename:
            pass
        filename=filename.replace('\\\\','\\')
        target_file=filename
        filename=filename.encode('utf-8')
        text = readFile(filename)
        mainEdit.set(text)
        mainEdit.set_pos(0)

def saveFileMenu():
        global target_file
        filename = appuifw.query(u"Save File",'text',target_file)
        if not filename:
            pass
        filename=filename.replace('\\\\','\\')
        target_file=filename
        filename=filename.encode('utf-8')
        text = mainEdit.get().encode('utf-8')
        text=text.replace("\xE2\x80\xA9","\x0D\x0A")
        saveFile(filename, text)
        appuifw.note(u"File Saved",'info')

def saveAsFileMenu():
        saveFileMenu()

def aboutMenu():
        appuifw.note(u"This Python Editor is made by vhly[FR]",'info')

def install_file_menu():
    global target_file
    e32.file_copy(u"e:\\system\\apps\\Python\\my\\"+os.path.split(target_file)[1],target_file)
    appuifw.note(target_file+' has installed','info')


def install_app_menu ():
    # Method body
    global target_file
    try:
        onl=standalone_install(target_file)
        appuifw.note(u"Install app to:"+onl,'info')
    except (Error,ValueError),err:
        lens=u" "
        fee=err.args
        noon=len(fee)
        for x in fee:
            lens=lens+'\n'+x
        appuifw.note(u"Error not install:"+lens,'error')

def genpyc():
    global target_file
    st=mainEdit.get().encode('utf-8')
    st=st.replace("\xE2\x80\xA9","\x0D\x0A")
    st=st.replace("\r","")
    cd=compile(st,target_file,'exec')
    magic=imp.get_magic()
    stamp=struct.pack('<i',time.time())
    base1=os.path.splitext(target_file)[0]
    cfile=open(base1+".pyc",'wb')
    cfile.write(magic)
    cfile.write(stamp)
    marshal.dump(cd,cfile)
    cfile.close()
    appuifw.note("Compile file to:\n"+base1+".pyc")
    pass


def genpyo():
    global target_file
    pass

def gen_tab():
    mainEdit.add(u"    ")

def gen_def():
    data=u"def "
    defname=appuifw.query(u"Method name",'text')
    if defname==None:
        pass
    data=data+defname+u"():\n    # Method body\n    \n"
    mainEdit.add(data)

def regUser ():
    # Method body
    imei_str=sysinfo.imei()
    sw_str=sysinfo.sw_version()
    fields=[(u"IMEI",'text',imei_str),(u"Name",'text'),(u"Code",'text')]
    frm=appuifw.Form(fields)
    frm.execute()

def newFileMenu ():
    # Method body
    mainEdit.clear()
    sup=u"# SYMBIANUID=\n# This file edited by Python Editor for S60\n#  gen by vhly[FR]\n#\n# Script Name:\n# Author:\n# Description:\n# \n\nimport e32\nfrom appuifw import *\nimport sys\n\napp_lock=e32.Ao_lock()\n\ndef exitApp():\n    sys.exit()\n    app_lock.signal()\n\napp.exit_key_handler=exitApp\n"
    mainEdit.set(sup)


def gotoEnd ():
    # Method body
    mainEdit.set_pos(mainEdit.len())
find_string=u"test"

def searchText ():
    # Method body
    global find_string
    sur=appuifw.query(u"Find String",'text')
    if not sur:
        pass
    find_string=sur
    poscurrent=mainEdit.get_pos()
    slen=mainEdit.len()
    slen=slen-poscurrent
    sur0=mainEdit.get(poscurrent,slen)
    index=sur0.find(sur)
    if index==-1:
        appuifw.note(u"Text not found",'info')
        pass
    poscurrent=poscurrent+index
    mainEdit.set_pos(poscurrent)

def searchNext():
    global find_string
    poscurrent=mainEdit.get_pos()
    slen=mainEdit.len()
    slen=slen-poscurrent
    sur0=mainEdit.get(poscurrent,slen)
    index=sur0.find(find_string)
    if index==-1:
        appuifw.note(u"Text not found",'info')
        pass
    poscurrent=poscurrent+index
    mainEdit.set_pos(poscurrent)

appuifw.app.menu = [(u"File",((u"New",newFileMenu),(u"Open",openFileMenu),(u"Save",saveFileMenu),(u"SaveAs",saveAsFileMenu))),(u"Edit",((u"Tab",gen_tab),(u"New def",gen_def),(u"Goto End",gotoEnd))),(u"Search",((u"Text",searchText),(u"Search next",searchNext))),(u"Install",((u"Script",install_file_menu),(u"App",install_app_menu))),(u"Compile",((u"PYC",genpyc),(u"PYO",genpyo))),(u"About",((u"About",aboutMenu),(u"Register",regUser)))]

appuifw.app.title=u"Python Editor"

# set the exit handler
appuifw.app.exit_key_handler = ex

# wait the lock
app_lock.wait()
[/code]
[yct02]

2007-4-20 11:03 vhly
<[hiD
e]vhly[FR][/hIde]>

2007-4-20 11:13 2ol
支持一下

2007-4-20 13:39 fudashuai
谢谢楼主分享~~~[s:23]

2007-4-20 14:18 上校sm
看不懂[s:25]

2007-4-20 14:38 114qq
赶什么用呢?
怎么用???

2007-4-22 23:14 zjj321
看的不太明白,向你学习一下,谢谢

2007-4-24 12:41 vhly
关于 Python 手机端

以上代码的功能描述

1。 提供使用手机编写Python脚本的能力
      虽然网上有很多文本编辑器,但是由于使用了Unicode编码,生成的文件不能被Python脚本运行环境所接受
      因此必须使用 utf-8编码,保存.py文件,也就是类似于 Windows 中记事本的功能,同时支持中文名称的文件名。

2。提供了直接安装脚本到Python系统目录的能力
     也就是当执行Python程序中的 Run Script菜单时,直接显示在列表中,免去了使用文件管理器的麻烦,也就是保存之后,可以
     直接运行了。

3。提供了生成可执行程序的能力
     本编辑器应该在 手机上运行。保存之后可以选择 Install Script->App 生成了一个可以在功能表里显示的程序,免去了使用
     Python选择脚本的麻烦。

4。提供简单的文本查找的能力
     区分大小写,可以查找文本,以及 Search Next

5。提供对文本编辑器中的代码进行编译的能力
     可以将打开的或者输入的代码编译成 pyc文件的能力。主要应用于 Python module lib,加快代码模块的家在速度。

6。提供了简单的模版
     提供了 新建脚本 时插入 appui 代码。提供新建 def 方法的功能

7。关于讲自身加入功能表的方法
     首先 使用文件管理器 运行 该脚本 名称比如为 pyEditor.py
     之后 在Python程序中运行 该脚本
     使用 pyEditor 编辑 自身的脚本文件 pyEditor.py

     选择 Install Script -> App

8。关于生成App程序时的注意事项

     1 应该在第一行加入如下代码
              # SYMBIANUID=0xXXXXXXXX           此处的内容为16近制的值 推荐 0x0123456x

        注意 pyEditor使用 0x01234560

     2 对于使用 File-> New 生成的代码 请注意第一行 已经包含了 上面的代码但是数值没有设定。
        如果要生成App文件 则必须设置

     3 如果不包含着一行 会出现提示 要求输入


Author: vhly[FR]
Date: 2007/04/24

2007-9-26 15:34 wshcyz
多谢啊!学习了。

2007-9-26 15:38 小萸儿
鼓励以下

2008-6-25 22:09 鹅鸡鸭
实在看不懂

页: [1]
查看完整版本: Python for S60 手机端


Powered by Discuz! Archiver 5.5.0  © 2001-2006 Comsenz Inc.