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() ('mail@mail.com','password') 登錄smtp服務器
收件人的電子郵件地址字符串,或多個收件人的字符串列表(作為“to”地址)。
電子郵件正文字符串必須以'Subject: \n'開頭,作為電子郵件的主題行。'\n'換行
>>> from email.mime.text import MIMEText
>>> msg = MIMEText('my name is python')
>>> msg['Subject']='Python Email'
>>> msg['From']='xxxx@163.com'
>>> s= smtplib.SMTP('smtp.163.com')
>>> s.login('xxxx@163.com','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 查看鍵盤鍵字符串




