1. return 0 只能用在 function 中,若要在執行到某條件時終止程式,要用exit()
2. 用 write 函式來寫檔時,注意裡面只能擺 string 型態的變數 和 字串!!
Traceback (most recent call last):
File "./Send_NIC_Traffic_To_POX.py", line 70, in <module>
out1.write(eth1_traffic)
TypeError: expected a character buffer object
所以 out1.write(eth1_traffic) 中的eth1_traffic要改成string寫入, str(eth1_traffic)
3. subprocess.call("可以擺字串 或 字串變數")
subprocess.call("snmpwalk -v2c -c public localhost .1.3.6.1.2.1.2.2.1.10 >> /wayne_code/NIC_traffic.txt",shell=True)
4. 字串處理函式 .split("=") 是依照=來切成兩半,會回傳List型態的變數回去,前半在list[0],後半在list[1]
.strip("")是去除字串中的空白字元之函式
5. [0:1]是取字串中第0個字元
[1:2]是取字串中第1個字元
[5:]是取第5個字元到最後一個字元
[:5]是取第0個字元到第4個字元
所以後面那個數字要 減1 就對摟!!
6. 字串*2 => 字串字串
ex: print('a'*2)
=> aa
所以從資料庫中取出來的 data,若其形態為string,要做數字運算前,記得先轉型為int
7. x = []
x[0] = 5 這樣是錯的喔!!
x.append(5) 因為List要用append才對唷!!!
8. 有時SQL命令回傳錯誤時,可直接在phpmyadmin中下SQL指令測看看~
小心空白格!! 會讓SQL錯誤唷!~
9. 用 Python 執行的 SQL語法 中,遇到 UPDATE, INSERT 要記得做 commit 喔!!
db = MySQLdb.connect(host="localhost", user="xxx", passwd="xxx", db="xxx")
cursor = db.cursor()
cursor.execute("update GA_JOIN_Info set outport=%s where Nu=%s", [str(GA_Server_Port[i]) , str(i)])
db.commit()
10. Python 2.7 使用 print 函式
print "Wayne = %s, Doris = %s" % row
Python 3以上:
print("XXX: %s" %variable)
11. dict 和 list 可以使用 del 刪除當中的部分元素
a = [1,2,3,4]
del a[1:3]
b = {'name':'fannys23', 'email':'test@fannys23.com', 'money':200}
del b['name']
12. 判斷檔案是否存在 的 Function
if not( os.path.exists("/wayne_code/NIC_eth1_Traffic_Information") ):
如果 NIC_eth1_Traffic_Information此檔案 不存在的話,則...
13. POX中的程式做資料庫(MySQL)連線後,再呼叫 GA程式 ,GA程式也有資料庫的存取,
此時執行完GA程式後,POX的程式再去存取DB中的資料,會因為沒有重新與DB做連線,所以
得到的資料是舊的。
解法:
POX呼叫GA程式時,先關閉DB連線( db.close() ),等執行完GA後,再重新連線做DB存取。
14.在 Windows 上執行sendto()函式後,出現TypeError,原因是Python 3之後的版本,
在sendto的第一個argument都必須用binary來指定。
Error訊息:
TypeError: sendto() takes exactly 3 arguments (2 given)
修正:
data = b'wayne_test'
s.sendto(data, (str(host), port))
15. Keyerror
發生原因: 當你去存取dictionary,但是所指定的key沒有在dictionary中時,所引發的Error
解法:取check存取字典時,key的型態要去確認(有些必須是int, ex: ofnexus._connections[] ),另外key的值也要去確認唷!!
原文解釋:
Python raises a KeyError whenever a dict() object is requested (using the format a = adict[key]) and the key is not in the dictionary.
16. ping去check server 是否還活著的「快速module」
在Controller上使用較快速的ping module,會去check Server是否還alive
取代了subprocess.call("ping -c 1 %s" % ip, shell=True)的作法(因為直接用ping指令要等封包回應實在太慢了...)。
下載位置:https://bitbucket.org/delroth/python-ping/downloads
安裝:
cd crc16-0.1.1
python setup.py build
sudo python setup.py install
使用:
ret = ping.do_one(ip, timeout=1, psize=64)
if ret is not None:
#ping有回應
else:
#ping沒回應
17. Python for-loop 整理
range(0, 256, 8) => 0, 8 ,16, 24...248 (到256的上一個數字)
range(10, 0, -2) => 10, 8, 6, 4, 2 (到0的上一個數字)
參考自:http://ez2learn.com/index.php/python-tutorials/python-tutorials/172-for
- # x從1到100
- for x in range(1, 101):
- sum += x
- # 印出數字加總的總合
- print '1 + 2 + 3 + ... + 100 =', sum
- # 建立List
- myList = [5, 5, 6, 6, 7, 7, 8, 8]
- # 我們一樣也可以使用索引的方式來存取List之類的物件
- # 從0到len(myList)
- for i in range(len(myList)):
- # print後留一個 , 表示不要換行
- print myList[i],
- # 換行
- # 印出0 2 4 6 8
- for i in range(0, 10, 2):
- print i,
- # 換行
- # 印出10 8 6 4 2
- for i in range(10, 0, -2):
- print i,
- # 換行
18. Python 數學Library
import math
math.log(x[, base]) => math.log(8, 2) => 3
19. 用 logging 來取代 print
好處:當不想要印出debug資訊時,只需把 logging.basicConfig(level=logging.DEBUG) 的 debug 模式關掉即可!!
不用像以前用print時還要去做註解的動作.....
- some.py
import logging
log = logging.getLogger( __name__ ) #從main中取得logging設定
def doSome(text):
log.debug(text)
def main():
logging.basicConfig(level=logging.DEBUG)
dosome("test")
if __name__ == '__main__':
main()
只要把第二行的 logging.basicConfig(level=logging.DEBUG) 中的 level 換成別的level: logging.basicConfig(level=logging.INFO)。
這樣子的話,程式中為了除錯所加的 debug 訊息就不會再出現了。
參考:http://www.icoding.co/2012/08/logging-html
20. if __name__ == "__main__": 的寫法解釋
__name__屬性
如果你使用python指令直接執行某個.py檔案,則__name__屬性會被設定為'__main__'名稱,
如果是import語句匯入模組,則__name__會被設定為模組名稱。
Ex:
def main():
logging.basicConfig(level=logging.DEBUG)
log.debug((CV_value([399934, 360495, 389073,481082] ) ) )
if __name__ == '__main__': #If this program execute by manually, then execute main()
main()
21. dir()函式 => 可以列出某Module裡頭可使用的屬性
ex:
import logging
log = logging.getLogger( __name__ )
def main():
logging.basicConfig(level=logging.DEBUG)
log.debug( dir(random) ) #Print the attributes in random module
if __name__ == '__main__': #If this program execute by manually, then execute main()
main()
Result:
DEBUG:__main__:['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', 'WichmannHill', '_BuiltinMethodType', '_MethodType', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_acos', '_ceil', '_cos', '_e', '_exp', '_hashlib', '_hexlify', '_inst', '_log', '_pi', '_random', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'division', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'jumpahead', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']
