486
技術社區[雲棲]
python 小技巧備注
最近陸陸續續寫了很多python的小腳本
記下一點東西方便以後查閱
#1.調用sqlite3數據庫 con=sqlite3.connect(xxx) con.text_factory = str #防止中文亂碼 cur=con.cursor() cur.execute("xx")#執行語句 con.commit()#寫入數據庫 #2.獲取剪切板內容 def getText(): w.OpenClipboard() try: d = w.GetClipboardData(win32con.CF_TEXT) w.EmptyClipboard() w.CloseClipboard() return d except: w.CloseClipboard() return '' def setText(aString): w.OpenClipboard() w.EmptyClipboard() w.SetClipboardData(win32con.CF_TEXT, aString) #如果是中文要重新編碼 w.CloseClipboard() #3.隨父線程結束的子線程 tee=threading.Thread(target=read) tee.setDaemon(True) #設置跟隨父線程 tee.start() #4.調用dll from win32con import * from ctypes import * user32=windll.LoadLibrary('user32.dll') user32.MessageBoxW(0,'PASS!'.decode('utf-8'),'WIN'.decode('utf-8'),0|MB_SYSTEMMODAL) #5.全局鍵盤鼠標監聽 多線程 hm = pyHook.HookManager() hm.KeyUp=ee #抬起函數 hm.KeyDown = onKeyboardEvent #按下函數 返回值均要為True,不然會死鎖 hm.HookKeyboard() #開始監聽 # pythoncom.PumpMessages()#循環獲取消息 GUI中不需要 hm.UnhookKeyboard()#解除監聽,不解除進程會假死,而且會無法關閉 #6.模擬鍵盤輸入 from win32api import * keybd_event(76,0,0,0)#76為相應鍵碼,按下 keybd_event(76,0,2,0)#抬起 def output(c=""): #輸出字符串,這邊符號隻設置了底下幾種,其他均沒設置 for j in range(len(c)): i=str(c[j]) flag=0;t=0 if i.islower(): i=i.upper();t=ord(i) elif i.isupper(): flag=1;t=ord(i) elif i=='@': flag=1;t=ord('2') elif i=='_': flag=1;t=189 elif i=='-': t=189 elif i=='.': t=190 else: t=ord(i) if flag==1: keybd_event(16,0,0,0) keybd_event(t,0,0,0) keybd_event(t,0,2,0) if flag==1: keybd_event(16,0,2,0) #7.獲取含某字符串的窗口hwnd hhwd=0;#hwnd def iterate(hwnd,nouse): global hhwd if IsWindow(hwnd) and IsWindowEnabled(hwnd) and IsWindowVisible(hwnd): if GetWindowText(hwnd).find('Mozilla Firefox')!=-1: hhwd=hwnd return True EnumWindows(iterate, 0) #8.置頂窗口 windll.user32.SwitchToThisWindow(hwnd,True) #經測試這種最有效 #9.按hwnd關閉窗口 win32gui.SendMessage(hhwd,WM_CLOSE,0,0) #10.清空Text ok.delete(0.0,END) ok.insert(END,'123') #11.遍曆文件夾並改名 def rename(): path=eny_path.get() for a,v,c in os.walk(path): t=len(str(int(len(c)/2))) for n in c: p=os.path.splitext(n) x=p[0] while len(x)<t: x='0'+x x=x+p[1] os.rename(os.path.join(a,n),os.path.join(a,x)) #12.利用喇叭蜂鳴…… winsound.Beep(1500,400) #13.注冊主程序析構函數 def xxit(): pass atexit.register(xxit) #14.利用lamba給button等傳遞參數 Button(text='bad',command=lambda:change(1),hei=1,width=5) #15.置頂Tkinter窗口 root.wm_attributes('-topmost',1) #16.通過代理聯網 from urllib import quote import cookielib, urllib2 class uu(): # 準備cookie cj = cookielib.LWPCookieJar() cookie_support = urllib2.HTTPCookieProcessor(cj) # 設置代理服務器 proxy_info = { 'host' : 'mengqidlufei.jks5.com' , 'port' :52385 } proxy_support = urllib2 . ProxyHandler ( { 'http' : \ 'https://%(host)s:%(port)d' % proxy_info } ) # 構造opener def __init__(self): opener = urllib2.build_opener(self.cookie_support, self.proxy_support) urllib2.install_opener(opener) # 打開網頁 def open(self,url): # print quote(url,':/=?') page = urllib2.urlopen(quote(url,':/=?')) t= page.read() page.close() return t #17.修改係統時間,3倍 import os,time,subprocess def changetime(t): l=time.localtime(t) dat="date %u-%02u-%02u"%(l.tm_year,l.tm_mon,l.tm_mday) tm="time %02u:%02u:%02u"%(l.tm_hour,l.tm_min,l.tm_sec) subprocess.Popen(dat, shell=True) subprocess.Popen(tm, shell=True) print 'ok' def change(): t=time.time() while 1: t+=60 changetime(t) time.sleep(20) #18.py2exe win32的dll錯誤解決辦法 from distutils.core import setup import py2exe,os includes = ["encodings", "encodings.*"] mfcfiles = [os.path.join(mfcdir, i) for i in ["mfc90.dll", "mfc90u.dll", "mfcm90.dll", "mfcm90u.dll", "Microsoft.VC90.MFC.manifest"]] data_files = [("Microsoft.VC90.MFC", mfcfiles),] #加入mfc文件 options = {"py2exe": { "compressed": 1, "optimize": 2, "includes": includes, # "bundle_files": 1 } } setup( version = "3.0", description = xxx, name = xxx, options = options, data_files = data_files, # zipfile=None, windows=[{"script": "v3.0.pyw" }], ) #19.PMW打包問題 #1.首先切換到源目錄下:C:\Python27\Lib\site-packages\Pmw\Pmw_1_3_3\bin #2.然後執行 python bundlepmw.py C:\Python27\Lib\site-packages\Pmw\Pmw_1_3_3\lib (注意是lib) #3.然後會在bin下生成個Pmw.py (貌似2.0生成的有問題) #4.複製Pmw.py和lib裏的PmwBlt.py和PmwColor.py到要打包的文件夾下 #5.按常規打包即可
最後更新:2017-04-03 21:30:16