https://www.jianshu.com/p/926869935071python
本文後面會逐步清理linux
Python2.0增長了新的用來存儲文本數據的類型:Unicode對象。它能夠用於存儲和操做Uounicode 數據(參見 http://www.unicode.org/),與現有的字符串兼容性良好,必要時能自動轉換。git
Unicode支持全部字符的表示,以前的ASCII只支持256個字符。更多Unicode相關的資料,參見:http://zh.wikipedia.org/wiki/Unicode。github
建立Unicode字符串:web
>>> u'Hello World !' u'Hello World !'
引號前的'u'表示Unicode 字符串,轉義的方式能夠建立其餘字符:正則表達式
>>> u'Hello\u0020World !' u'Hello World !'
轉義序列\u0020表示插入編碼爲0x0020(空格)的Unicode 字符。shell
其餘字符也會直接解釋爲對應的編碼值。 許多西方國家使用的標準Latin-1編碼的字符串和編碼小於256的Unicode字符和在Unicode編碼中的同樣。apache
使用ur能夠取消轉義,r表示原始格式(raw)。django
>>> ur'Hello\u0020World !' u'Hello World !' >>> ur'Hello\\u0020World !' u'Hello\\\\u0020World !'
若是你須要大量輸入反斜槓(好比正則表達式),原始模式很是有用。編程
除了標準編碼,Python還支持其餘編碼。
內置函數unicode()能夠訪問全部註冊的Unicode編碼(COders和DECoders),並支持Latin-1 、ASCII、UTF-8和UTF-16 之類的編碼能夠互相轉換,後兩個是變長編碼。一般默認編碼爲 ASCII,此編碼接受0到127 這個範圍的編碼,不然報錯。Unicode字符串打印或寫入到文件,或者使用str()轉換時,使用默認編碼進行轉換操做。
encode()方法能夠把Unicode字符串轉換爲特定編碼的8bit字符串,參數爲小寫的編碼名做爲參數。
反之可使用unicode()把其餘編碼轉換爲unicode。
>>> u"abc" u'abc' >>> str(u"abc") 'abc' >>> u"äöü" u'\xe4\xf6\xfc' >>> str(u"äöü") Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128) >>> u"äöü".encode('utf-8') '\xc3\xa4\xc3\xb6\xc3\xbc' >>> unicode('\xc3\xa4\xc3\xb6\xc3\xbc', 'utf-8') u'\xe4\xf6\xfc'
下面使用python打開火狐,搜索引擎上輸入seleniumhq,而後退出。
import time from selenium import webdriver from selenium.webdriver.common.keys import Keys browser = webdriver.Firefox() browser.get('http://www.so.com/') assert '360' in browser.title elem = browser.find_element_by_name('q') # Find the search box elem.send_keys('seleniumhq' + Keys.RETURN) time.sleep(3) browser.quit()
下面腳本在畫圖軟件上畫出一系列正方形。Linux上能夠用Pinta演示,注意要打開一個空白畫圖頁面在屏幕左上角。
import pyautogui distance = 100 pyautogui.moveTo(300, 300) while distance > 0: pyautogui.dragRel(distance, 0, duration=0.5) # move right distance -= 5 pyautogui.dragRel(0, distance, duration=0.5) # move down pyautogui.dragRel(-distance, 0, duration=0.5) # move left distance -= 5 pyautogui.dragRel(0, -distance, duration=0.5) # move up
#!/usr/bin/python # -*- coding: utf-8 -*- import logging import logging.handlers import time import re import os.path import subprocess32 import sys sys.path.append('../lib/') from requests.auth import HTTPDigestAuth dial_logger = logging.getLogger('MyLogger') dial_logger.setLevel(logging.DEBUG) fh = logging.handlers.RotatingFileHandler( '../logs/dial_log_server.log', maxBytes=10000000, backupCount=5) fh.setLevel(logging.DEBUG) formatter = logging.Formatter(u'%(asctime)s [%(levelname)s] %(message)s') fh.setFormatter(formatter) dial_logger.addHandler(fh) dial_logger.info("Application starting! \n") while True: for line in open("../conf/url.csv"): try: now = time.strftime("%Y-%m-%d_%H:%M:%S", time.gmtime()) print(now) name, git_url, branch, jenkins_url = line.strip().split(',') # print(name, git_url, branch, jenkins_url) dial_logger.info("Beginning Scan {0}! \n".format(name)) dial_logger.info("{0} {1} {2}! \n".format(git_url, branch, jenkins_url)) cmd = "git ls-remote -h " + git_url result = subprocess32.check_output(cmd,shell=True) #print(result) version = re.findall(r'(\S+)\s+{0}'.format(branch), result, re.MULTILINE)[0] dial_logger.info("current version: {0}! \n".format(version)) file_name = '/tmp/{0}'.format(name) if os.path.exists(file_name): old_version = open(file_name).read().strip() # print(old_version, version) dial_logger.info("old version: {0}! \n".format(old_version)) if old_version == version: dial_logger.info("Don not call {0} \n".format(name)) print("Don not call {0} \n".format(name)) continue f = open(file_name,'w') f.write(version) f.close() dial_logger.info("Call {0} \n".format(jenkins_url)) cmd = "curl --user xurongzhong:123456 -s {0} &".format(jenkins_url) # print(cmd) dial_logger.info("command: {0}! \n".format(cmd)) subprocess32.call(cmd, shell=True) except Exception as e: dial_logger.error(str(e), exc_info=True) dial_logger.info("End Scan! \n") time.sleep(3 * 60)
除了前面介紹的 while 語句,Python還更多的流程控制工具。
軟件自動化測試是利用特殊軟件(跟被測軟件比較)來控制測試執行並比較實際結果與預測結果。自動化測試能夠在測試過程當中自動化一些重複性的但必要的任務, 或者增長手工難以執行的額外的測試,好比性能測試、壓力測試,模擬測試、接口測試、單元測試等。自動化測試通常具有準備測試環境、測試控制、判斷結果和測試報告的功能。
測試框架生成用戶界面的事件,如按鍵和鼠標點擊,並觀察用戶界面的變化結果,以驗證該觀測到的行爲的程序是否正確。
許多測試自動化工具提供的記錄和回放功能,讓用戶可以記錄用戶的交互行動和重播。這種方法的優勢是它須要不多或根本沒有軟件開發。可是稍有改變,維護工做就比較大。
web測試是GUI的變種,它是閱讀的HTML不是觀察窗口事件,使用的技術有很大差別。selenium是知名的web測試工具,selenium有python api,參見:https://pypi.python.org/pypi/selenium。
對類,模塊或庫的公共接口進行測試。一種日益增加的趨勢是在軟件開發使用的測試框架,如xUnit框架(例如, pytest和unittest)容許代碼進行單元測試。
代碼驅動的自動化測試是敏捷軟件開發的一個重要特色。這種方法的支持者認爲,它生產的軟件,是更可靠,成本更低。
API測試也被普遍使用,由於GUI的自動化測試的成本過高。
測試開發基於框架或者編程調用應用的接口,好比SNMP,COM,HTTP經常使用的接口,命令行等。
PyAutoGUI跨平臺且人性化的GUI自動化工具。
PyAutoGUI是編程控制鼠標和鍵盤的Python模塊。
PyAutoGUI可用pip工具安裝在PyPI下載。
PyAutoGUI旨在提供跨平臺、人性化的Python GUI自動化模塊,API的設計是儘量的簡單。
例如移動屏幕中間:
>>> import pyautogui >>> screenWidth, screenHeight = pyautogui.size() >>> pyautogui.moveTo(screenWidth / 2, screenHeight / 2)
PyAutoGUI能夠模擬移動鼠標,點擊鼠標,拖動鼠標,按鍵,按住鍵和按鍵盤熱鍵組合。
>>> import pyautogui >>> screenWidth, screenHeight = pyautogui.size() >>> currentMouseX, currentMouseY = pyautogui.position() >>> pyautogui.moveTo(100, 150) >>> pyautogui.click() >>> pyautogui.moveRel(None, 10) # move mouse 10 pixels down >>> pyautogui.doubleClick() >>> pyautogui.typewrite('Hello world!', interval=0.25) # type with quarter-second pause in between each key >>> pyautogui.press('esc') >>> pyautogui.keyDown('shift') >>> pyautogui.press(['left', 'left', 'left', 'left', 'left', 'left']) >>> pyautogui.keyUp('shift') >>> pyautogui.hotkey('ctrl', 'c')
顯示對話框
>>> import pyautogui >>> pyautogui.alert('This is an alert box.') 'OK' >>> pyautogui.confirm('Shall I proceed?') 'Cancel' >>> pyautogui.confirm('Enter option.', buttons=['A', 'B', 'C']) 'B' >>> pyautogui.prompt('What is your name?') 'Al' >>> pyautogui.password('Enter password (text will be hidden)') 'swordfish'
>>> import pyautogui >>> im1 = pyautogui.screenshot() >>> im1.save('my_screenshot.png') >>> im2 = pyautogui.screenshot('my_screenshot2.png')
下面腳本在畫圖軟件上畫出一系列正方形。Linux上能夠用Pinta演示,注意要打開一個空白畫圖頁面在屏幕左上角。
import pyautogui distance = 200 pyautogui.moveTo(300, 300) while distance > 0: pyautogui.dragRel(distance, 0, duration=0.5) # move right distance -= 5 pyautogui.dragRel(0, distance, duration=0.5) # move down pyautogui.dragRel(-distance, 0, duration=0.5) # move left distance -= 5 pyautogui.dragRel(0, -distance, duration=0.5) # move up
依賴
Windows: 無
OS X: AppKit和Quartz模塊須要PyObjC,須要先安裝pyobjc-core,再安裝pyobjc。
Linux:python-xlib (for Python 2) or python3-Xlib (for Python 3)
容錯
Linux 的窗口的關閉在左上角,要儘可能避免錯誤地點擊到關閉,設置「pyautogui.FAILSAFE = True」便可。
設置sleep: "pyautogui.PAUSE = 2.5", 單位爲秒,默認爲0.1。
安裝
Windows: 「pip.exe install pyautogui」
OS X:
# sudo pip3 install pyobjc-core # sudo pip3 install pyobjc # sudo pip3 install pyautogui
Linux:
ubuntu
# sudo pip3 install python3-xlib # sudo apt-get scrot # sudo apt-get install python-tk # sudo apt-get install python3-dev # sudo pip3 install pyautogui
ubuntu 14.04安裝:
# pip install svn+ # sudo apt-get install scrot # apt-get install python-tk
OS X: AppKit和Quartz模塊須要PyObjC,須要先安裝pyobjc-core,再安裝pyobjc。
Linux:python-xlib (for Python 2) or python3-Xlib (for Python 3)
快速入門
通用函數
>>> import pyautogui >>> pyautogui.position() # current mouse x and y (968, 56) >>> pyautogui.size() # current screen resolution width and height (1920, 1080) >>> pyautogui.onScreen(300, 300) # True if x & y are within the screen. True
容錯
>>> import pyautogui >>> pyautogui.PAUSE = 2.5 >>> import pyautogui >>> pyautogui.FAILSAFE = True
fail-safe爲True時,移動到左上角會觸發pyautogui.FailSafeException異常。
鼠標函數
其餘實例:
肯定圖片位置:
>>> import pyautogui >>> button7location = pyautogui.locateOnScreen('button.png') # returns (left, top, width, height) of matching region >>> button7location (1416, 562, 50, 41) >>> buttonx, buttony = pyautogui.center(button7location) >>> buttonx, buttony (1441, 582) >>> pyautogui.click(buttonx, buttony) # clicks the center of where the button was found
返回圖片的中心位置:
>>> import pyautogui >>> buttonx, buttony = pyautogui.locateCenterOnScreen('button.png') # returns (x, y) of matching region >>> buttonx, buttony (1441, 582) >>> pyautogui.click(buttonx, buttony) # clicks the center of where the button was found
持續集成(Continuous integration CI)是天天合併全部開發的做拷貝到共享主線若干次的軟件工程實踐。由Grady Booch1991年在的Booch方法提出,儘管Booch的不主張每日屢次集成,所以CI未必老是頻繁集成。CI被主張每日屢次集成XP(extreme programming)採用。CI的主要目的是防止集成問題,在XP早期描述中稱爲「集成警鐘」。
最初在XP中CI是與測試驅動開發的實踐中的自動化單元測試結合使用,在開發者的本地環境經過全部單元測試再提交到主線。這有助於防止開發人員的工做的代碼相互覆蓋。若是有必要能夠用實際功能代替Mock等。後面引進了構建服服務器。自動按期甚至每次提交都執行單元測試並報告結果。
除了運行單元測試和集成測試,也引入了質量控制。好比靜態和動態測試,衡量和profile性能,從代碼提取物文檔以方便手工QA流程。
持續交付擴展了持續集成,確保在主線軟件始終處於可部署到用戶的狀態,使實際部署過程很是迅速。
儘早集成,儘快發現問題。輔以自動單元、集成測試。
代碼倉庫:維護一個代碼倉庫,管理代碼、文檔、配置文件等全部產出。儘可能少使用分支。
自動編譯:包含編譯的二進制文件,生成文檔、網站頁面、統計和發佈媒體(好比Debian DEB,紅帽RPM或Windows MSI文件)等。
編譯自測。
每人天天都提交到基線
每次提交都有構建
快速構建
準上線環境(staging)
使容易交付:測試和相關人員能夠了解構建、儘早測試。
全部人能夠看到最近構建結果。
自動部署
好處:
儘早發現集成錯誤,容易跟蹤,節省了時間和金錢。
避免發佈日期的混亂。
當單元測試失敗或bug出現時,若是須要很容易回退。
當前構建適合測試,演示,或發佈。
頻繁的check-in推進開發建立模塊化的,不太複雜的代碼。
強制頻繁執行自動化測試
本地更改,即時反饋系統範圍的影響。
自動化測試與CI的指標(如度量代碼覆蓋率,代碼的複雜性和特性完整性等)引導開發人員開發功能完整,高質量的代碼。
自動化測試須要大量的工做、涉及框架開發、新功能的覆蓋和舊功能的維護。
python中有很多自動編譯工具。https://en.wikipedia.org/wiki/List_of_build_automation_software 列出了很多自動編譯工具,其中buildbot、scons等工具爲python書寫。比較出名的爲buildbot、scons、buildout及jenkins相關插件。
waftools https://pypi.python.org/pypi/waftools
waf https://waf.io/
TravisPy https://pypi.python.org/pypi/TravisPy
taschenmesser https://pypi.python.org/pypi/taschenmesser
cuppa https://pypi.python.org/pypi/cuppa
numscons https://pypi.python.org/pypi/numscons
PyScons https://pypi.python.org/pypi/PyScons
teamcity-messages https://pypi.python.org/pypi/teamcity-messages
syncloud-image-ci https://pypi.python.org/pypi/syncloud-image-ci
mac https://pypi.python.org/pypi/mac
jenkinsapi https://pypi.python.org/pypi/jenkinsapi
django-jenkins https://pypi.python.org/pypi/django-jenkins
platformio https://pypi.python.org/pypi/platformio
gump http://gump.apache.org/
buildbot https://pypi.python.org/pypi/buildbot
tunir https://pypi.python.org/pypi/tunir
zc.buildout https://pypi.python.org/pypi/zc.buildout
SCons是能自動分析源代碼文件的依賴性和操做系統的要求計算機軟件構建工具,並生成最終的二進制文件。它相似於基於make和autoconf的傳統的GNU編譯系統。
SCons基於Python,軟件項目配置和構建過程的實現都是Python腳本。
主要特色以下:
配置文件是Python腳本。
內置C,C ++和Fortran自動依賴分析的。依賴性分析是可擴展的,經過用戶定義的依賴掃描器能夠支持其餘語言或類型的文件。而GNU編譯器集的(GCC) 的內建依賴分析基於正則表達式掃描。
內置支持C,C ++,D,Java,Fortran,Objective-C,Yacc的,Lex,Qt和SWIG,以及TeX和LaTeX文檔的支持。
支持中央庫源代碼和預先構建。
內置支持從版本控制系統,如SCCS,RCS,CVS,Subversion,BitKeeper和Perforce。
內置支持微軟的Visual Studio,包括生成DSP,.DSW,的.sln和的.vcproj文件。
使用MD5簽名檢查文件內容的變化,可配置傳統的時間戳。好比設置SourceSignatures('timestamp')。
支持並行構建。
集成類Autoconf支持來查找#include文件,庫、函數和typedef。
支持全部依賴的全局視圖,所以不須要屢次編譯和和從新序的目標文件。
在cache共享構建文件。
跨平臺。
此部分參考資料:https://www.ibm.com/developerworks/cn/linux/l-cn-scons/
編輯文件: helloscons.c
#include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]) { printf("Hello, SCons!\n"); return 0; }
如今咱們想編譯helloscons.c爲二進制文件helloscons,即相似gcc helloscons.c -o helloscons的功能。
建立文件:SConstruct
Program('helloscons.c')
編譯
$ scons scons: Reading SConscript files ... scons: done reading SConscript files. scons: Building targets ... gcc -o helloscons.o -c helloscons.c gcc -o helloscons helloscons.o scons: done building targets. $ scons scons: Reading SConscript files ... scons: done reading SConscript files. scons: Building targets ... scons: `.' is up to date. scons: done building targets.
編譯類型:
Program: 編譯成可執行程序(在 Windows 平臺上便是 exe 文件),這是最經常使用的一種編譯類型。
Object: 只編譯成目標文件。使用這種類型,編譯結束後,只會產生目標文件。在 POSIX 系統中,目標文件以 .o 結尾,在 Windows 平臺上以 .OBJ 結尾。
Library: 編譯成庫文件。SCons 默認編譯的庫是指靜態連接庫。
StaticLibrary: 顯示的編譯成靜態連接庫,與上面的 Library 效果同樣。
SharedLibrary: 在 POSIX 系統上編譯動態連接庫,在 Windows 平臺上編譯 DLL。
Java: 編譯Java程序。好比 Java(‘classes’,‘src’),其中的src表示源碼目錄。
修改可執行文件名字
Program('myscons, 'helloscons.c')
靜默模式
$ scons -Q gcc -o helloscons.o -c helloscons.c gcc -o myscons helloscons.o
多文件編譯
Program('helloscons2', ['helloscons2.c', 'file1.c', 'file2.c'], LIBS = 'm', LIBPATH = ['/usr/lib', '/usr/local/lib'], CCFLAGS = '-DHELLOSCONS
模糊匹配:
Program('helloscons2', Glob('*.c')
配置文件中 LIBS,LIBAPTH 和 CCFLAGS 是 SCons 內置的關鍵字,它們的做用以下:
LIBS: 顯示的指明要在連接過程當中使用的庫,若是有多個庫,應該把它們放在一個列表裏面。這個例子裏,咱們使用一個稱爲 m 的庫。
LIBPATH: 連接庫的搜索路徑,多個搜索路徑放在一個列表中。這個例子裏,庫的搜索路徑是 /usr/lib 和 /usr/local/lib。
CCFLAGS: 編譯選項,能夠指定須要的任意編譯選項,若是有多個選項,應該放在一個列表中。這個例子裏,編譯選項是經過 -D 這個 gcc 的選項定義了一個宏 HELLOSCONS。
$ scons -Q gcc -o file1.o -c -DHELLOSCONS file1.c gcc -o file2.o -c -DHELLOSCONS file2.c gcc -o helloscons2.o -c -DHELLOSCONS helloscons2.c gcc -o helloscons2 helloscons2.o file1.o file2.o -L/usr/lib -L/usr/local/lib -lm
環境變量
env = Environment() env.Append(CPPFLAGS=['-Wall','-g']) env.Program('hello', ['hello.c', 'main.c'])
聯繫做者:徐榮中 python開發自動化測試羣113938272 微博 http://weibo.com/cizhenshi。
python 2.7 英文官方教程:https://docs.python.org/2/tutorial/
IBM scons 中文介紹:
維基百科 scons 英文介紹https://en.wikipedia.org/wiki/SCons
scons github地址:https://github.com/azatoth/scons
維基百科GNU build system英文介紹: https://en.wikipedia.org/wiki/GNU_build_system
scons bitbucket wiki:https://bitbucket.org/scons/scons/wiki/Home
rtthread-manual-doc scons 中文簡介: https://github.com/RT-Thread/rtthread-manual-doc/blob/master/zh/1chapters/10-chapter_scons.md
scons主頁:http://www.scons.org/