概述:Android开发中常用的python脚本

图片压缩(tinypng)

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

"""
导入Tinify
pip install --upgrade tinify
"""

import os
import sys
import os.path
import tinify

# 去https://tinypng.com/developers申请API KEY
tinify.key = "你申请到的API KEY" # API KEY

# 压缩的核心
def compress_core(input_file, output_file, img_width, img_height):
source = tinify.from_file(input_file)
if img_width is not -1:
resized = source.resize(
method = "scale",
width = img_width,
height = img_height
)
resized.to_file(output_file)
else:
source.to_file(output_file)

# 压缩一个文件夹下的图片
def compress_path(path, width, height):
print ("compress_path-------------------------------------")
if not os.path.isdir(path):
print ("not a dir!")
return
else:
input_path = path # 源路径
output_path = path+"/tiny" # 输出路径
print ("input_path = %s" %input_path)
print ("output_path = %s" %output_path)

for root, dirs, files in os.walk(input_path):
print ("root = %s" %root)
print ("dirs = %s" %dirs)
print ("files = %s" %files)
for name in files:
file_name, file_suffix = os.path.splitext(name)
if file_suffix == '.png' or file_suffix == '.jpg' or file_suffix == '.jpeg':
output_full_path = output_path + root[len(input_path):]
output_full_name = output_path + '/' + name
if os.path.isdir(output_full_path):
pass
else:
os.mkdir(output_full_path)
compress_core(root + '/' + name, output_full_name, width, height)
break # 仅遍历当前目录

if __name__ == "__main__":
compress_path(os.getcwd(), -1, -1)

查找项目中同名文件

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os

names = set()

def check_file(name):
if ".java" in name:
if name in names:
print name
else:
names.add(name)


def find_file(level, name):
rrrrdir = level + name
srcfiles = os.listdir(rrrrdir)
for srcfile in srcfiles:
srcfilepath = level + name + "/" + srcfile
if os.path.isdir(srcfilepath):
find_file(level + name + "/", srcfile)
else:
if "/." not in srcfilepath:
if "/java" in srcfilepath:
if "build" not in srcfilepath:
if "Test" not in srcfilepath:
check_file(srcfile)


srcdir = os.getcwd()
name = ""
find_file(srcdir, name)

根据字符串生成二维码

#coding:utf-8
'''
Python将Url生成二维码图片

安装PIL:pip install pillow
安装qrcode:pip install qrcode
'''

__author__ = 'Jinlin'

import sys
import qrcode
import os

#生成二维码图片
def make_qr(url,save):
qr=qrcode.QRCode(
version=5, #生成二维码尺寸的大小 1-40 1:21*21(21+(n-1)*4)
error_correction=qrcode.constants.ERROR_CORRECT_M, #L:7%的字码可被容错 M:15%的字码可被容错 Q:25%的字码可被容错 H:30%的字码可被容错
box_size=10, #每个格子的像素大小
border=1, #边框的格子宽度大小(默认是4)
)
qr.add_data(url)
qr.make(fit=True)

img=qr.make_image()
img.save(save)

if __name__=='__main__':
save_path='theqrcode.png' #生成后的保存文件
str = '测试'
# if sys.version_info < (3, ):
# str=raw_input('请输入要生成二维码的文本内容:')
# else :
# str=input('请输入要生成二维码的文本内容:')

make_qr(str, save_path)