如今的時間適合寫點最近的小總結,這中間涉及到python/git等問題,我就從python先提及吧.html
1、Pythonpython
1. Python的異常處理git
由於想到本身不斷嘗試寫小程序的話會用到拋出異常信息來判斷哪裏出現了問題:正則表達式
usage: raise [Exception [, args [, trackback]]]
上面是Python的raise的用法,下面是本身用這個方法實現異常的拋出方法:小程序
1 def check_args(args): 2 if not args.host: 3 msg = 'Args missing! One of the following args should be specified \n' \ 4 '--host 192.168.1.1 \n' \ 5 '-f TargetFile \n' 6 raise Exception(msg) 7 8 #參考別人的代碼模式,我這樣寫來拋出異常.
2. list轉strsocket
這個問題是由於本身的無知吧:函數
命令行傳入的host(即ip地址)是list形式,想要經過list轉爲str的格式以後來進行socket.connect(),報錯:
本身想象的姿式:
client.connect((str(args.host), args.p))
正確的姿式:
client.connect((''.join(args.host), args.p))
上圖證實本身的愚蠢(可能下次還會犯一樣的錯):url
3. argparse函數spa
出發的動機是由於本身寫的小程序要經過命令行的形式傳參並執行命令.命令行
用本身的簡單小實例來顯示函數的具體用法吧:
1 def parse_args(): 2 parser = argparse.ArgumentParser(prog = 'hello', 3 formatter_class = argparse.RawTextHelpFormatter, 4 description = '* A tiny toy for fun *\n' 5 'By ST(www.********)', 6 usage = 'hellPLC.py [options]') 7 parser.add_argument('-host', metavar = 'HOST [HOST2 HOST3 ...]', type = str, 8 default = '', nargs = '*', 9 help = 'Scan the host form command line')
代碼很簡單,一看就懂大概函數是什麼樣子,重點是add_argument的參數,當你傳入的cmd參數是這種方式的話:
咱們能夠看到,須要在-p以後跟一個int型的參數才能夠,還有另一種形式.
parser.add_argument('-p', metavar = 'PORT', type = int, default = '')
這種方式不須要跟參數,只須要相似於"python -h"這種形式就能夠執行並獲得想要的結果:
這裏就須要對這個函數的各個參數的功能有個基本的瞭解,這樣才能用起來舒服.
1 parser.add_argument('-b', default= False, dest='b', action='store_true', 2 help = 'Get the base info')
下圖就是咱們能夠跟的參數,本身的問題就是區分清楚action和dest這兩個參數,還有default,type等.
4. 正則匹配
5. 格式化字符串
1 temp = '123456' 2 print("word:%s" %temp) 3 4 output: word:123456
很簡單就能夠搞定,可是當時想要返回取多個返回值,一會兒矇住不知道怎麼搞了,呵呵了~
1 f.write ("Block Type: %s \n" 2 "Block count: %s \n" 3 %(block_type, block_count)) 4 return block_type, block_count
代碼很容易看,就是這樣,搞定了.
先到這裏,都是小問題,作個記錄