print(‘’):#打印字符串 shell实现方法:echo
input():#获取键盘输入 shell实现方法:read
len():#获取字符串长度 shell实现方法:${#str}
round():浮点数四舍五入 shell: echo "scale=2;2.34*6.66" | bc
continue:退出当前循环,进入下一路新的循环,shell实现方法一样
max( x, y, z, .... ) 返回给定参数的最大值,参数可以为序列。
join() 返回通过指定字符连接序列中元素后生成的新字符串。
range(10):生成列表 shell实现方法:seq 10 或者{1..10}
random.randint(a,b) #import random生成随机数;shell实现方法 $(($RANDOM%50+1))
random.sample(list,#) 从list随机获取#个元素
random.seed(datetime.datetime.now()) 随机数种子
sys.exit : 提前结束程序 ,shell 实现方法 :exit
a=['cat', 'bat', 'rat', 'elephant']
list.sort(key=str.lower) 按照普通字典排序
get(key,key1) 判断字典如果key不存在,返回key1
setdefault(key,key1) 为键设置一个默认值
#!/usr/bin/python36 import pprint message = 'It was a bright cold day in April, and the clocks were striking thirteen.' count = {} for m in message: count.setdefault(m,0) count[m] = count[m] +1 pprint.pprint(count)
from module_name import function_name 导入模块中指定函数
from module_name import function_name as fn 指定fn别名
class dog(): def __init__(self,name,age): """初始化属性name和age""" self.name = name self.age = age def sit(self): print(self.name.title() + ' is now sitting.') ##self.name.title() 首字母大写 def rollOver(self): print(self>name.title() + 'rolled over!')
class ElectricCar(Car): def __init__(self, make, model, year): """初始化父类的属性""" super().__init__(make, model, year) self.batterySize = 70 self.battery = Battery() #将实例用作属性,Battery()类的实例为 ElectricCar类的一个属性
super() 是一个特殊函数,帮助Python将父类和子类关联起来。这行代码让Python调用ElectricCar 的父类的方法 __init__() ,让 ElectricCar 实例包含父类的所有属性。
upper() 全部字母转换为大写 shell:tr [a-z] [A-Z]
lower() 全部字符转换为小写 shell: tr [A-Z] [a-z]
isalpha()返回 True,如果字符串只包含字母,并且非空;
isalnum()返回 True,如果字符串只包含字母和数字,并且非空;
isdecimal()返回 True,如果字符串只包含数字字符,并且非空;
isspace()返回 True,如果字符串只包含空格、制表符和换行,并且非空;
istitle()返回True,如果字符串仅包含以大写字母开头、后面都是小写字母的单词。
startswith() 方法返回 True,它所调用的字符串以该方法传入的字符串开始
endswith() 方法返回 True,它所调用的字符串以该方法传入的字符串结束
'#'.join(['My', 'name', 'is', 'Simon'])
rjust(#,str) 右对齐 #表示字符串长度,str表示填写字符,默认空格
#!/usr/bin/python36 def Pic(Dict,lw,rw): print('PICNIC ITEMS'.center(lw + rw ,'-')) for m,n in Dict.items(): print(m.ljust(lw,'.') + str(n).rjust(rw)) picnicItems = {'sandwiches': 4, 'apples': 12, 'cups': 4, 'cookies': 8000} Pic(picnicItems,10,5)
strip(str) 删除开头和末尾的空白字符 ,str表示删除指定的字符 Abcd :表示删除出现的A、b、c、d
2.用 re.compile()函数创建一个 Regex 对象(记得使用原始字符串)。
3.向 Regex 对象的 search()方法传入想查找的字符串。它返回一个 Match 对象。
4.调用 Match 对象的 group()方法,返回实际匹配文本的字符串。
正则表达式字符串中的第一对括号是第 1 组(str.group(1)),第二对括号是第 2 组(str.group(2))。
>>> batRegex = re.compile(r'Bat(man|mobile|copter|bat)')
>>> mo = batRegex.search('Batmobile lost a wheel')
第二种含义:声明非贪心匹配 Python默认为贪心模式,匹配最长字符串 花括号的“非贪心”版本匹配尽可能最短的字符串,即在结束的花括号后跟着一个问号(ha){3,5}? 匹配最小字符串
re.compile(r'[a-z]',re.I) 不区分大小写
re.compile('.*', re.DOTALL) 让.匹配换行符
re.compile('foo', re.IGNORECASE | re.DOTALL) 不区分大小写,并且句点字符匹配换行符
re.compile('',re.VERBOSE) 忽略正则表达式字符串中的空白符和注释
1.如果调用在一个没有分组的正则表达式上,例如\d\d\d-\d\d\d-\d\d\d\d,方法findall()将返回一个匹配字符串的列表,例如['415-555-9999', '212-555-0000']。
2.如果调用在一个有分组的正则表达式上,例如(\d\d\d)-(\d\d\d)-(\d\d\d\d),方法 findall()将返回一个字符串的元组的列表(每个分组对应一个字符串),例如[('415','555', '1122'), ('212', '555', '0000')]
第一个参数是一个字符串,用于取代发现的匹配。第二个参数是一个字符串,即正则表达式。第三个参数是替换次数,默认为0 全部替换。
sub()的第一个参数中,可以输入\1、\2、\3……。表示“在替换中输入分组 1、2、3……的文本
>>> namesRegex = re.compile(r'Agent \w+')
>>> namesRegex.sub('CENSORED', 'Agent Alice gave the secret documents to Agent Bob.')
'CENSORED gave the secret documents to CENSORED.'
>>>b= re.sub('\n+', " ", content)
\w 任何字母、数字或下划线字符(可以认为是匹配“单词”字符)
>>> os.path.join('root','download','test')
>>> os.path.join('root','download','test')
os.path.abspath(path) 返回参数的绝对路径的字符串
os.path.isabs(path) 参数是一个绝对路径返回True ,否则返回False
os.path.relpath(paht,start) 返回从 start 路径到 path 的相对路径的字符串
os.path.dirname(path) 返回参数中最后一个斜杠之前的所有内容(目录名称)
os.path.basename(path) 返回参数中最后一个斜杠之后的所有内容 (文件名称)
os.path.split(path) 返回 目录名称和基本文件 的字符串元组
>>> os.path.split('/root/python/if.py')
os.path.splitext(path) 返回文件名和扩展名
os.path.splitext('/tmp/test/1.txt')
endswith() 方法用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False。
str.endswith(suffix[, start[, end]])
>>> 'abcd!!!.txt'.endswith('.txt',7,11)
os.path.getsize(path) 返回 path 参数中文件的字节数
os.path.exists(path) 如果 path 参数所指的文件或文件夹存在,返回True
os.path.isfile(path) 如果 path 参数存在,并且是一个文件,返回True
os.path.isdir(path) 如果 path 参数存在,并且是一个文件夹,返回True
os.rmdir(path) 将删除 path 处的文件夹。该文件夹必须为空,其中没有任何文件和文件夹。
open(file,'w') 以写模式打开文件,覆写原有的文件
2.调用 File 对象的 read()或 write()方法。
3.调用 File 对象的 close()方法,关闭该文件。
>>>with open("/tmp/foo.txt") as file:
可以将 Python 程序中的变量保存到二进制的 shelf 文件中。
shelve.open() 传入文件名,将返回的值保存在一个变量中。
>>> cats = [{'name': 'Zophie', 'desc': 'chubby'}, {'name': 'Pooka', 'desc': 'fluffy'}]
"[{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}]"
>>> fileObj = open('myCats.py', 'w')
>>> fileObj.write('cats = ' + pprint.pformat(cats) + '\n')
shutil.copy(source,destination) 将路径source 处的文件复制到路径destination处的文件夹(source 和 destination 都是字符串)
shutil.copytree(source, destination) 将路径 source 处的文件夹,包括它的所有文件和子文件夹,复制到路径 destination 处的文件夹
shutil.move(source, destination),将路径 source 处的文件夹移动到路径destination,并返回新位置的绝对路径的字符串。
shutil.rmtree(path) 将删除 path 处的文件夹,它包含的所有文件和文件夹都会被删除。
send2trash.send2trash() 将文件和文件夹删除到回收站
zipfile.ZipFile() 调用zip对象,第二个参数‘w’ ,以写模式打开 'a' 添加模式打开。
namelist() 返回 ZIP 文件中包含的所有文件和文件夹的字符串的列表。
>>> a=zipfile.ZipFile('test.zip')
['test/', 'test/1/', 'test/1/2/', 'test/1/2/3/', 'test/1.txt', 'test/2.txt', 'test/3.txt', 'test/4.txt', 'test/5.txt', 'test/6.txt']
getinfo() 返回一个关于特定文件的 ZipInfo 对象
extractall() 从 ZIP 文件中解压缩所有文件和文件夹,放到当前工作目录中。
extract() 从 ZIP 文件中解压缩单个文件到当前目录或指定目录
write() 第一个参数是一个字符串,代表要添加的文件名。第二个参数是“压缩类型”参数,它告诉计算机使用怎样的算法来压缩文件 compress_type=zipfile.ZIP_DEFLATED。
traceback.format_exc() 得到反向跟踪字符串
assert 关键字 条件, 当条件为False时显示的字符串
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s- %(message)s')
logging.basicConfig(filename='myProgramLog.txt', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
loggin.disable(logging.CRITICAL) 禁止日志
DEBUG logging.debug() 最低级别。用于小细节。通常只有在诊断问题时,你才会关心这些消息
INFO logging.info() 用于记录程序中一般事件的信息,或确认一切工作正常
WARNING logging.warning() 用于表示可能的问题,它不会阻止程序的工作,但将来可能会
ERROR logging.error() 用于记录错误,它导致程序做某事失败
CRITICAL logging.critical() 最高级别。用于表示致命的错误,它导致或将要导致程序完全停止工作
datetime.datetime.now() 返回当前时间
datetime.datetime.fromtimestamp() Unix 纪元时间戳 转换为datetime对象
>>> datetime.datetime.fromtimestamp(1557728114)
datetime.datetime(2019, 5, 13, 14, 15, 14)
datetime.timedelta() 接受关键字参数 weeks、days、hours、minutes、seconds、milliseconds 和 microseconds
>>> today = datetime.datetime.now()
>>> aboutYears = datetime.timedelta(days=365*18)
datetime.datetime(2037, 5, 8, 14, 35, 3, 697342)
>>> aboutYears.total_seconds()
halloween = datetime.datetime(2019, 10, 31, 0, 0, 0)
while datetime.datetime.now() < halloween:
strptime(time_string, format) 将字符串转换为datetime;函数返回一个 datetime 对象,它的时刻由time_string 指定,利用format 字符串参数来解析。
>>> datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
>>> datetime.datetime.strptime('05, 21, 2019', '%m, %d, %Y')
datetime.datetime(2019, 5, 21, 0, 0)
#!/usr/bin/python36 import threading,time print('start') def takeANap(): time.sleep(5) print('wake up') threadObj = threading.Thread(target=takeANap) threadObj.start() print('End ')
>>> threadObj = threading.Thread(target=print, args=['Cats', 'Dogs', 'Frogs'],kwargs={'sep': ' & '})
>>>subprocess.Popen('C:\\Windows\\System32\\calc.exe')
>>> subprocess.Popen('/usr/bin/top')
>>>subprocess.Popen(['C:\\Windows\\notepad.exe', 'C:\\hello.txt'])
>>> subprocess.Popen(['C:\\python34\\python.exe', 'hello.py'])
>>>subprocess.Popen(['start', 'hello.txt'], shell=True)
starttls() 让SMTP连接处于TLS模式,使用SSL,忽略
login() ('[email protected]','password') 登录smtp服务器
收件人的电子邮件地址字符串,或多个收件人的字符串列表(作为“to”地址)。
电子邮件正文字符串必须以'Subject: \n'开头,作为电子邮件的主题行。'\n'换行
>>> from email.mime.text import MIMEText
>>> msg = MIMEText('my name is python')
>>> msg['Subject']='Python Email'
>>> msg['From']='[email protected]'
>>> msg['To']='[email protected]'
>>> s= smtplib.SMTP('smtp.163.com')
>>> s.login('[email protected]','xxxxxx')
(235, b'Authentication successful')
ImageColor.getcolor() 返回RGBA元组
>>> ImageColor.getcolor('red', 'RGBA')
>>> ImageColor.getcolor('green', 'RGBA')
>>> catImg = Image.open('2.jpg')
Image.new(‘RGBA’,(#,#),‘颜色’) 返回空白图像
字符串'RGBA',将颜色模式设置为 RGBA(还有其他模式)
图像开始采用的背景颜色,是一个表示 RGBA 值的四整数元组。你可以用ImageColor.getcolor()函数的返回值作为这个参数。另外,Image.new()也支持传入标准颜色名称的字符串。
>>> im = Image.new('RGBA', (100, 200), 'purple')
>>> im.save('purpleImage.png')
>>> im2 = Image.new('RGBA', (20, 20))
>>> im2.save('transparentImage.png')
>>> cropImg = catImg.crop((100,110,230,300))
>>> imgLog = Image.open('log.png')
>>> catCopyimg = catImg.copy()
>>> catCopyimg.paste(imgLog,(156,248))
>>> catCopyimg.paste(imgLog,(156,248),imgLog) #粘贴透明图像
>>> newImg = catImg.resize((int(w/2),int(h/2)))
旋转 90 度或 270 度时,宽度和高度会变化,在 Windows 上,使用黑色的背景来填补旋转造成的缝隙,可选expand 关键字参数,如果设置为 True,就会放大图像的尺寸,以适应整个旋转
>>>catImg.rotate(90).save('90.png')
>>> catImg.rotate(90,expand=True).save('901.png')
必须向 transpose()方法传入 Image.FLIP_LEFT_RIGHT 或 Image.FLIP_TOP_BOTTOM
>>> catImg.transpose(Image.FLIP_LEFT_RIGHT).save('xuanzhuan.jpg')
>>> catImg.transpose(Image.FLIP_TOP_BOTTOM).save('xuanzhuan.jpg')
getpixel() 和 putpixel() 更改单个像素
>>> im = Image.new('RGBA', (100, 100))
im.putpixel((x,y),(110,110,110))
im.putpixel((x,y),ImageColor.getcolor('red','RGBA'))
from PIL import Image, ImageDraw
>>> from PIL import Image, ImageDraw
>>> im = Image.new('RGBA', (200, 200), 'white')
>>> draw.line([(0, 0), (199, 0), (199, 199), (0, 199), (0, 0)], fill='black')
>>> draw.rectangle((20, 30, 60, 60), fill='blue')
>>> draw.ellipse((120, 30, 160, 60), fill='red')
>>> draw.polygon(((57, 87), (79, 62), (94, 85), (120, 90), (103, 113)),fill='brown')
>>> for i in range(100, 200, 10):
draw.line([(i, 0), (200, i - 100)], fill='green')
可选参数 font 是一个 ImageFont 对象,用于设置文本的字体和大小。
第一个参数是字符串,表示字体的TrueType 文件,这是硬盘上实际的字体文件。TrueType 字体文件具有.TTF 文件扩展名,通常可以在以下文件夹中找到:
在 OS X 上:/Library/Fonts and /System/Library/Fonts。
在 Linux 上:/usr/share/fonts/truetype。
第二个参数是一个整数,表示字体大小的点数(而不是像素)。请记住,Pillow 创建的PNG 图像默认是每英寸 72 像素,一点是1/72 英寸。
>>> from PIL import Image, ImageDraw, ImageFont
>>> im = Image.new('RGBA', (200, 200), 'white')
>>> draw.text((20, 150), 'Hello', fill='purple')
>>> fontsFolder = 'FONT_ _FOLDER' # e.g. ‘/Library/Fonts’
>>> arialFont = ImageFont.truetype(os.path.join(fontsFolder, 'arial.ttf'), 32)
>>> draw.text((100, 150), 'Howdy', fill='gray', font=arialFont)
pip install PyGetWindow==0.0.1
pyautogui. FAILSAFE = False 禁止自动防故障功能
pyautogui.PAUSE = 1 每次pyautogui函数调用后暂停一秒
pyautogui.moveTo(x,y,duration) 将鼠标立即移动到指定位置,duration可选 移动所需秒数
pyautogui.moveRel(x,y,duration) 相对于当前位置移动鼠标x:向右移动多少像素 y:向左移动多少个像素
pyautogui.click(x,y,button=) 点击鼠标,默认点击左键
在当前位置以外的其他位置点击,传入x,y坐标, button 关键字参数,值分别为 'left'、'middle'或 'right'
相当于pyautogui. mouseDown() 和pyautogui.mouseUp()的封装
pyautogui.middleClick() 双击鼠标中建
pyautogui.dragRel()按下左键,相对于当前位置移动鼠标
pyautogui.moveTo()将鼠标移动到指定的x,y坐标
pyautogui.moveRel()相对于当前位置移动鼠标
#!python import pyautogui,time time.sleep(5) pyautogui.click() distance = 200 while distance > 0: pyautogui.dragRel(distance,0, duration=0.2) distance -= 5 pyautogui.dragRel(0,distance, duration=0.2) pyautogui.dragRel(-distance,0, duration=0.2) distance -= 5 pyautogui.dragRel(0,-distance, duration=0.2)
pyautogui.scroll(#)滚动鼠标,整数向上滚动, 负数向下滚动
pixelMatchesColor() 如果屏幕上指定的 x、y 坐标处的像素与指定的颜色匹配,返回true
>>> pyautogui.pixelMatchesColor(50, 200, (245, 245, 245))
>>> pyautogui.pixelMatchesColor(50, 200, (245, 245, 246))
函数返回4个整数的元组,是屏幕上首次发现该图像时左边的x 坐标、顶边的 y 坐标、宽度以及高度。
有多处,返回一个Generator,可以传递给list(),返回一个4整数元组列表。
>>> pyautogui.locateOnScreen('submit.png')
Box(left=2, top=108, width=83, height=72)
>>> pyautogui.center((2,108,83,72))
pyautogui.typewrite(‘str’,#) 向计算机发送虚拟按键,第二个参数暂停时间
>>> pyautogui.typewrite(['a', 'b', 'left', 'left', 'X', 'Y'])
pyautogui.KEYBOARD_KEYS 查看键盘键字符串