文章目录
1. import
import os
import math
import matplotlib.pyplot as plt
import pytesseract
from PIL import Image
import time
import matplotlib.image as mpimg
import subprocess
import threading
import sys
import re
import cv2
import numpy as np
import csv
import pandas as pd
import traceback
import datetime
2. 文件、目录
常用
os.path.exists() 文件夹是否存在
遍历目录
g = os.walk('./img/')
for par_dir, _, files in g:
for file in files:
full_path_i = os.path.join(par_dir, file)
if ( file.find(".JPEG") >=0):
print(file)
有空格的文件路径处理,加上引号""
目录删除、创建
import shutil
if os.path.exists(share_path+"vendor"):
shutil.rmtree(share_path+"vendor")
if not os.path.exists(share_path+"vendor"):
os.mkdir(share_path+'vendor')
读文件
def read_file(path):
try:
fd = open( path, 'rU', encoding='utf-8')
read_str = fd.read()
fd.close()
return read_str
except IOError:
return None
3. 时间
时间打印
import datetime
def LOGI( str_log):
print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f ") + str_log)
时间测量
import time
beg = time.time()
time.time() - beg
4.多线程–及线程锁
import threading
mult_thread_num = 0
mult_thread_mutex = threading.Lock()#锁的申明
#锁的加减
def addMultNum():
global mult_thread_num
if mult_thread_mutex.acquire(1):
mult_thread_num += 1 #AAD
mult_thread_mutex.release()
def decMultNum():
global mult_thread_num
if mult_thread_mutex.acquire(1):
mult_thread_num -= 1
mult_thread_mutex.release()
#线程函数
def ObjectText(img_path,file_name):
print('mult thread');
#创建启动线程added_thread
added_thread = threading.Thread(target=ObjectText,args=(par_dir, file))
added_thread.start()
5.多进程
#用多线程之后,感觉多进程用处不大
6.异常处理–打印trace
try :
data=pd.read_csv(file)
except KeyboardInterrupt: #ctrl+c to exit
break
except:
traceback.print_exc() ##打印trace
print('read error:')
finally:
print('finally ')
7.系统调用
系统调用返回函数
def getGitDiff():
cmd = "git diff"
pipe = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout
retstr = pipe.read()
return retstr
8.传入参数
import sys
print( '参数个数为:', len(sys.argv), '个参数。')
print( '参数列表:', str(sys.argv))
9. 键盘输入
temp = input()
11. 字符串处理
11.1 获取字串的数字
import subprocess
import re
def getPid():
retstr = subprocess.Popen("adb shell ps|grep -i 'camera.p'", shell=True, stdout=subprocess.PIPE).stdout.read()
pid = re.findall('\d+',retstr.decode()) #提取retstr 中数字
print(pid)
if (0 == len(pid)):
return "0";
return (pid[0])
12. 网络下载
url = 'http://www.pythontab.com/test/demo.zip'
urllib.urlretrieve(url, "demo.zip")
13. numpy的使用
菜鸟教程里很详细
https://www.runoob.com/numpy/numpy-array-manipulation.html
常见使用
属性
ndarray.shape ndarray.size ndarray.dtype ndarray.data
数组操作
reshape
flatten:展开拷贝 ravel:展开
数学函数
NumPy 包含大量的各种数学运算的函数,包括三角函数,算术运算的函数,复数处理函数等。
位运算
print (‘将 10 左移两位:’)
print (np.left_shift(10,2))
文件读写
参考 NumPy 中文网https://www.numpy.org.cn/reference/routines/io.html#%E6%96%87%E6%9C%AC%E6%96%87%E4%BB%B6
文本文件
方法 | 描述 |
---|---|
loadtxt(fname[, dtype, comments, delimiter, …]) | 从文本文件加载数据。 |
savetxt(fname, X[, fmt, delimiter, newline, …]) | 将数组保存到文本文件。 |
genfromtxt(fname[, dtype, comments, …]) | 从文本文件加载数据,并按指定方式处理缺少的值。 |
fromregex(file, regexp, dtype[, encoding]) | 使用正则表达式解析从文本文件构造数组。 |
fromstring(string[, dtype, count, sep]) | 从字符串中的文本数据初始化的新一维数组。 |
ndarray.tofile(fid[, sep, format]) | 将数组以文本或二进制形式写入文件(默认)。 |
ndarray.tolist() | 以Python标量的a.ndim级深嵌套列表的形式返回数组。 |
#原始二进制文件
方法 | 描述 |
---|---|
fromfile(file[, dtype, count, sep, offset]) | 从文本或二进制文件中的数据构造数组。 |
ndarray.tofile(fid[, sep, format]) | 将数组以文本或二进制形式写入文件(默认)。 |