android使用Python脚本编译侯建我们所需要的所有的库

这篇博客介绍了如何使用Python脚本编译Android所需的库,涉及环境配置、Python模块使用,如urllib2、open方法、os.path以及subprocess。文章详细解释了相关Python函数的用途,如文件操作、路径检查和权限设置,并展示了通过Python执行终端命令下载Android SDK的过程,探讨了进程间通信和文件权限等问题。
摘要由CSDN通过智能技术生成

使用Python需要注意的一些事项

比如我们想使用modules库下的common.py的类,我们得导入,但是导入的话如果没有__init__文件的话导入不了的,这点得注意

from modules import common

__init__.py,为什么必须得使用这个呢

这个跟java有点区别,java中只要是在一个项目中的所有的类都可以通过包名导入,Python,__init__.py 文件的作用是将文件夹变为一个Python模块,Python 中的每个模块的包中,都有__init__.py 文件。

通常__init__.py 文件为空,但是我们还可以为它增加其他的功能。我们在导入一个包时,实际上是导入了它的__init__.py文件。这样我们可以在__init__.py文件中批量导入我们所需要的模块,而不再需要一个一个的导入。

原来这个文件的所有其实就相当我们java中的构造函数一下,默认的话是为空的,但是如果我们想要在初始化的时候做一些初始化动作,我们可以在里面做出一些处理。这样理解就很方便了。

 

这个做完以后我们得配置环境,进行下载andorid sdk,然后我们在安装相应的依赖

那么如何通过脚本实现下载android sdk 呢

def download_sdk():
    """
    Download the SDK from Google
    """

    url = ""
    url_macosx = "https://dl.google.com/android/android-sdk_r24.0.2-macosx.zip"//mac电脑下的下载android sdk
    url_linux = "https://dl.google.com/android/android-sdk_r24.3.4-linux.tgz"//对于linux下的下载

    if sys.platform == "linux2":
        url = url_linux
    else:
        url = url_macosx

    file_name = url.split('/')[-1]//这里的-1的意思就是数据的最后一个数
    u = urllib2.urlopen(url)//用于进行网络请求的
    f = open(common.getConfig("rootDir") + "/" + file_name, 'wb')//函数用于打开一个文件,创建一个 file 对象,相关的方法才可以调用它进行读写。这里的common.getConfig(xxx)就是从我们的setting.properties文件读取相应的键值对的值,这里的这个值就是我们的项目的根目录,我们希望再次后面添加我们要下载文件的文件名,wb的意思是:	以二进制格式打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。
    meta = u.info()
    file_size = int(meta.getheaders("Content-Length")[0])
    common.logger.debug("Downloading: %s \r\n FileName: %s \r\n FileSize: \r\n %s" % (url, file_name, file_size))

    block_sz = file_size / 100
    count = 0
    while True:
        buffer = u.read(block_sz)
        if not buffer:
            break

        f.write(buffer)
        count = count + 1
        if count % 10 == 0:
            sys.stdout.write('\r[{0}] {1}%'.format('#' * (count / 10), count))
            sys.stdout.flush()

    f.close()
//上面就是进行io流的读写然后进行一些显示屏幕的展示
    androidSDKZIP = f.name
    print common.term.cyan + str(common.config.get('qarkhelper', 'FILE_DOWNLOADED_TO')) + androidSDKZIP.decode(
        'string-escape').format(t=common.term)
    print common.term.cyan + str(common.config.get('qarkhelper', 'UNPACKING')) + androidSDKZIP.decode(
        'string-escape').format(t=common.term)
//上面这个是对相应位置的一个File downloaded to/Users/zew/mysvn/xxx/xxx/android-sdk_r24.0.2-macosx.zip
\nUnpacking  Android SDK Manager.../Users/zew/mysvn/xxx/xxx/android-sdk_r24.0.2-macosx.zip
    //判断是否是linux
    if sys.platform == "linux2":
        try:
            if not os.path.exists(androidSDKZIP.rsplit(".", 1)[0])://这里的就是/Users/zew/mysvn/qark/qark/android-sdk_r24.0.2-macosx
                os.makedirs(androidSDKZIP.rsplit(".", 1)[0])//如果没有的话就创建这个文件夹
            extract(androidSDKZIP, androidSDKZIP.rsplit(".", 1)[0])
        except Exception as e:
            logger.error(e.message)
        common.writeKey('AndroidSDKPath', androidSDKZIP.rsplit(".", 1)[0] + "/android-sdk-linux/")
    else:
        zf = zipfile.ZipFile(androidSDKZIP)//进行一次解压
        for filename in [zf.namelist()]://然后解压完了遍历
            try:
                if not os.path.exists(androidSDKZIP.rsplit(".", 1)[0]):
                    os.makedirs(androidSDKZIP.rsplit(".", 1)[0])
                zf.extractall(androidSDKZIP.rsplit(".", 1)[0] + "/", zf.namelist(), )//这里我们通过暴力解压的方式把这个zip文件进行解压。
            except Exception as e:
                logger.error(e.message)
            else:
                logger.info('Done')
        common.writeKey('AndroidSDKPath', androidSDKZIP.rsplit(".", 1)[0] + "/android-sdk-macosx/")//这个操作是把android sdk的路径写进配置文件中方便下次直接使用
    # We dont need the ZIP file anymore
    os.remove(androidSDKZIP)//然后我们再删除那个zip包,因为以后我们已经不再需要了
    run_sdk_manager()

 

那里面有这么一个问题file_name = url.split('/')[-1],这个-1代表什么意思呢?

下面我们走一段代码

def split():
    line = 'a+b+c+d'
    print line.split('+')[-1]


if __name__ == "__main__":
    split()

打印结果是:d

那就是说[-1]的意思就是那个数组的最后一个位置-1。大家不要觉得我这个分享下载依赖这个功能的时候给你们讲一些语法是个累赘,我们从小学习汉语一开始说什么,都是教你喊爸爸,妈妈,然后过于去学校学习语法,英语也是开始“how are you ”,"I am fine thank you",我在这里先教你去说也就是去使用,然后遇到了问题再教你语法上的东西,方便大家快速的对一门语言的掌握。

 

urllib2是什么东西

模块定义的函数和类用来获取URL(主要是HTTP的),他提供一些复杂的接口用于处理: 基本认证,重定向,Cookies等

按照他的官网文档说在Python3中它已经被分成几个模块,但是我们现在使用的是2.7版本暂时依然去使用这个模块进行网络请求,

urllib2.urlopen(url[, data[, timeout[, cafile[, capath[, cadefault[, context]]]]])
Open the URL url, which can be either a string or a Request object.

data may be a string specifying additional data to send to the server, or None if no such data is needed. Currently HTTP requests are the only ones that use data; the HTTP request will be a POST instead of a GET when the data parameter is provided. data should be a buffer in the standard application/x-www-form-urlencoded format. The urllib.urlencode() function takes a mapping or sequence of 2-tuples and returns a string in this format. urllib2 module sends HTTP/1.1 requests with Connection:close header included.

数据可能是一个字符串,指定要发送给服务器的其他数据,或者如果不需要这些数据,则为None。目前,HTTP请求是唯一使用数据的请求;当提供数据参数时,HTTP请求将是POST而不是GET。数据应该是标准application/x-www-form-urlencoding格式中的缓冲区。urllib.urlencode()函数接受2元组的映射或序列,并以这种格式返回字符串。urllib2模块发送带有连接的HTTP/1.1请求:包含关闭报头。

The optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default timeout setting will be used). This actually only works for HTTP, HTTPS and FTP connections.

可选的timeout参数指定了一个以秒为单位的超时,用于阻塞操作,比如连接尝试(如果没有指定,将使用全局默认超时设置)。这实际上只适用于HTTP、HTTPS和FTP连接。

If context is specified, it must be a ssl.SSLContext instance describing the various SSL options. See HTTPSConnection for more details.

如果指定了上下文,则必须是ssl。描述各种SSL选项的SSLContext实例。有关详细信息,请参阅HTTPSConnection。

The optional cafile and capath parameters specify a set of trusted CA certificates for HTTPS requests. cafile should point to a single file containing a bundle of CA certificates, whereas capath should point to a directory of hashed certificate files. More information can be found in ssl.SSLContext.load_verify_locations().

可选的cafile和capath参数为HTTPS请求指定一组受信任的CA证书。cafile应该指向一个包含一组CA证书的文件,而capath应该指向一个散列证书文件的目录。更多信息可以在ssl.SSLContext.load_verify_locations()中找到。

The cadefault parameter is ignored.
忽略cadefault参数。
This function returns a file-like object with three additional methods:
这个函数返回一个类文件的对象,另外还有三个方法:

geturl() — return the URL of the resource retrieved, commonly used to determine if a redirect was followed
info() — return the meta-information of the page, such as head
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值