本文爲參加老男孩Python自動化運維課程第三天學習內容的總結。html
大體內容以下:python
一、文件操做編程
二、字符編碼轉碼相關操做數組
三、函數app
0、關於本文中全部運行Python代碼的環境:運維
--操做系統:Ubuntu 16.10 (Linux 4.8.0)python2.7
--Python版本:3.5.2編程語言
python2.7.12ide
--Python IDE: PyCharm 2016.3.2函數式編程
靜夜思
牀前明月光,
疑是地上霜。
舉頭望明月,
低頭思故鄉。
1 # Step# 1 & 2: open a file with read mode, and assign to f 2 f = open("LiBai_a_tranquil_night.txt", "r", encoding="utf-8") 3 4 # Step#3: read the content from f 5 try: 6 for line in f: 7 print(line) 8 finally: 9 f.close() # Step#4: close the file 10 11 --------------- 執行結果 --------------- 12 靜夜思 13 14 牀前明月光, 15 16 疑是地上霜。 17 18 舉頭望明月, 19 20 低頭思故鄉。
二、文件打開模式:
1)r: 只讀模式,不可寫。打開文件後,文件指針(光標)默認定位在文件開頭。
1 f = open("LiBai_a_tranquil_night.txt", "r", encoding="utf-8") 2 3 # check the if the f is writable 4 print(f.writable()) # False 5 6 f.write("\ntry to write a new line") # cannot write, got "io.UnsupportedOperation: not writable"
2)w:寫模式,若是文件不存在,則建立;若文件已存在,則覆蓋。打開文件後,文件指針(光標)默認定位在文件開頭。在寫模式下文件不可讀。
1 # open file with write mode 2 f = open("LiBai_a_tranquil_night.txt", "w", encoding="utf-8") 3 4 # not readable 5 print(f.readable()) # False 6 7 f.write("write line") 8 f.close() 9 10 f = open("LiBai_a_tranquil_night.txt", "r", encoding="utf-8") 11 try: 12 for line in f: 13 print(line) 14 finally: 15 f.close() # close the file 16 17 ----------------------- 執行結果 ------------------------ 18 False 19 write line
3)a:追加寫模式,只能將新增的內容追加到文件末尾。此時文件不可讀。 打開文件後,文件指針(光標)默認定位在文件末尾。
1 # open a file with append mode, and assign to f 2 f = open("LiBai_a_tranquil_night.txt", "a", encoding="utf-8") 3 4 # check if the f is a readable file 5 print(f.readable()) # False 6 7 f.write("李白") # write a new content 8 9 f = open("LiBai_a_tranquil_night.txt", "r", encoding="utf-8") 10 11 print("file content after append new content".center(60, "=")) 12 # Step#3: read the content from f 13 try: 14 for line in f: 15 print(line) 16 finally: 17 f.close() # Step#4: close the file 18 19 -------------------------- 執行結果 ----------------------- 20 False 21 ===========file content after append new content============ 22 靜夜思 23 24 牀前明月光, 25 26 疑是地上霜。 27 28 舉頭望明月, 29 30 低頭思故鄉。李白
4)r+:讀寫模式,打開文件後,文件指針(光標)默認定位在文件開頭;若是不是在文件末尾寫入,會將原來位置的字符替換。
# open file with r+ mode f = open("LiBai_a_tranquil_night.txt", "r+", encoding="utf-8") print(f.readable()) # True print(f.writable()) # True print("cursor position is : %s" % f.tell()) # cursor position after open file try: f.write("aaa") # write "aaa" in the first line finally: f.close() f = open("LiBai_a_tranquil_night.txt", "r", encoding="utf-8") try: for line in f: print(line) finally: f.close() -------------- 執行結果 ------------- True True cursor position is : 0 aaa is there you when there are few people around making me feel good? Why is there you when there are few people around making me feel good?
5)w+:寫讀模式,與w模式相似,打開文件後,會把文件內容清空;若是文件不存在,則建立。可是w+模式支持讀、寫。文件指針(光標)默認定位在文件開頭。
1 # open file with w+ mode 2 f = open("LiBai_a_tranquil_night.txt", "w+", encoding="utf-8") 3 print(f.readable()) # True 4 print(f.writable()) # True 5 print("cursor position is : %s" % f.tell()) # cursor position after open file 6 7 try: 8 f.write("aaa") # write "aaa" in the first line 9 f.flush() 10 f.seek(0, 0) # seek the cursor to the first line first character 11 print("after write".center(60, "=")) 12 for line in f: 13 print(line) 14 finally: 15 f.close() 16 17 -------------- 執行結果 --------------- 18 True 19 True 20 cursor position is : 0 21 ========================after write========================= 22 aaa
6)a+:追加讀寫模式,與a模式相似,可是支持讀、寫。打開文件會,默認光標在文件末尾。
1 # open file with a+ mode 2 f = open("LiBai_a_tranquil_night.txt", "a+", encoding="utf-8") 3 print(f.readable()) # True 4 print(f.writable()) # True 5 print("cursor position is : %s" % f.tell()) # cursor position after open file 6 7 try: 8 f.write("bbb") # write "aaa" in the first line 9 f.flush() 10 f.seek(0, 0) # seek the cursor to the first line first character 11 print("after write".center(60, "=")) 12 for line in f: 13 print(line) 14 finally: 15 f.close() 16 17 -------------- 執行結果 -------------- 18 True 19 True 20 cursor position is : 142 21 ========================after write========================= 22 Why is there you when there are few people around making me feel good? 23 24 Why is there you when there are few people around making me feel good? 25 26 bbb
7)b:以二進制模式讀取、寫入文件內容,通常與a、w、r結合使用,如rb,ab, wb,ab+。 在open方法,不要指定encoding方式,以二進制讀取。
1 # open file with ab+ mode 2 f = open("LiBai_a_tranquil_night.txt", "ab+") 3 print(f.readable()) # True 4 print(f.writable()) # True 5 print("cursor position is : %s" % f.tell()) # cursor position after open file 6 7 try: 8 f.write(b"bbb") # write "bbb" in binary 9 f.flush() 10 f.seek(0, 0) # seek the cursor to the first line first character 11 print("after write".center(60, "=")) 12 for line in f: 13 print(line) 14 finally: 15 f.close() 16 17 --------------- 執行結果 --------------- 18 True 19 True 20 cursor position is : 145 21 ========================after write========================= 22 b'Why is there you when there are few people around making me feel good?\n' 23 b'Why is there you when there are few people around making me feel good?\n' 24 b'bbbbbb'
8)U:與r、r+結合做用,在讀取時,自動過濾到\r、\n、\r\n等爲\n。
三、文件操做:
f.close(): 關閉打開過的文件。
f.fileno(): 返回文件在內存中編號。
f.tell(): 返回當前光標所在位置。
f.isatty(): 若是打開的文件是一個終端文件(如打印機文件),返回真;
f.read(): 讀取文件全部內容。對於大文件不要用read()方法,會把內存佔滿。
f.write(): 寫入文件內容。
f.readable(): 判斷打開的文件是否可讀取。
f.writeable(): 判斷打開的文件是否可寫。
f.seek(offset, whence): 從新定位光標位置,whence表示當前光標位置,有3個值(1表示當前光標所在位置開始算起,offset只能爲0; 2表示文件結束位置開始算起,offset只能爲0; 0表示從文件天頭位置開始算起);offset表示偏移量。
1 f = open("LiBai_a_tranquil_night.txt", "r", encoding="utf-8") 2 print("current cursor is : %s" % f.tell()) 3 4 f.seek(0, 1) # move the cursor to current position 5 print("current cursor is : %s" % f.tell()) 6 7 f.seek(3, 0) # move the cursor to the first line 3rd character 8 print("current cursor is : %s" % f.tell()) 9 10 f.seek(0, 2) # move the cursor to the last character 11 print("current cursor is : %s" % f.tell()) 12 13 f.close() 14 15 ------------------ 執行結果 ------------------ 16 current cursor is : 0 17 current cursor is : 0 18 current cursor is : 3 19 current cursor is : 153
f.seekable(): 是否能夠改變光標位置
f.truncate(): 清空從光標位置開始以後的全部文件內容,返回光標所在位置,與r+、a+結合使用。
1 f = open("LiBai_a_tranquil_night.txt", "a+", encoding="utf-8") 2 print("current cursor is : %s" % f.tell()) 3 4 f.seek(12, 0) # move the cursor to 12th character 5 6 print(f.truncate()) # truncate the file content from cursor positon 7 8 print("current cursor is : %s" % f.tell()) 9 10 f.close() 11 12 ------------ 執行結果 ----------- 13 current cursor is : 153 14 12 15 current cursor is : 12
四、with語句:能夠自動關閉打開的文件,不用手動關閉,即當with代碼塊執行完畢時,python內部會自動關閉並釋放文件資源
1 with open("LiBai_a_tranquil_night.txt", "r", encoding="utf-8") as f: 2 print(f.readline()) # print the 1st line 3 4 with open("LiBai_a_tranquil_night.txt", "r", encoding="utf-8") as f1, \ 5 open("LiBai_a_tranquil_night11.txt", "r", encoding="utf-8") as f2: 6 print(f1.readline()) # print the 1st line 7 print(f2.readline()) # print the 1st line
五、文件操做練習:模擬sed命令替換文件內容
1 # replace the "我愛北京天安門" to "我愛 Beijing" in the file "sed_text.txt" 2 3 # the string will be replaced 4 find_str = "北京天安門" 5 # new string 6 new_str = " Beijing" 7 8 list_lines = list([]) 9 10 with open("sed_text.txt", 'r+', encoding="utf-8") as f: 11 print("Before replace".center(60, "*")) 12 for line in f: # read each line in the file 13 print(line.strip()) 14 if line.find(find_str) >= 0: # find the content which need to be replaced 15 line = line.replace(find_str, new_str) 16 list_lines.append(line) 17 18 f.seek(0, 0) # go back to the 1st character 19 f.truncate() # truncate the file content 20 for i in range(len(list_lines)): # write the new content to the file 21 f.write(list_lines[i]) 22 23 print("After replace".center(60, "*")) 24 f.seek(0, 0) 25 for line in f: 26 print(line.strip()) 27 28 --------------- 執行結果 ------------------------ 29 ***********************Before replace*********************** 30 我愛北京天安門 31 天安門上太陽升 32 偉大領袖毛主席 33 指引咱們向前進 34 我愛北京天安門 35 天安門上太陽升 36 偉大領袖毛主席 37 指引咱們向前進 38 ***********************After replace************************ 39 我愛 Beijing 40 天安門上太陽升 41 偉大領袖毛主席 42 指引咱們向前進 43 我愛 Beijing 44 天安門上太陽升 45 偉大領袖毛主席 46 指引咱們向前進
一、在python2中 , 默認的字符編碼爲ASCII(僅限英文);要輸入中文時,須要在python代碼開頭加上「-*- coding:utf-8 -*-」聲明語句。
在python3中默認爲UTF-8(屬於unicode的一種, 是unicode的擴展),可不須要加「-*- coding:utf-8 -*-」 語句;
二、在python2中,將ASCII編碼(英文)、GB2312(中文)等 轉換成機器能識別的unicode編碼(這個過程稱爲decode),而後再轉換成用戶想要看到的編碼類型如GBK、UTF-8等,(這個過程稱爲encode)。
1 #!/usr/bin/python 2 # -*- coding:utf-8 -*- 3 # encoding & decoding in Python2 4 # transfer from UTF-8 to GB2312, then to GBK; then Transfer back to UTF-8 5 # Spencer Jiang 6 # 2017-03-21 7 8 import sys 9 10 # default coding type in Python2 is ASCII 11 print("\nThe default coding type in \033[1;35m Python%s \033[0m is : \033[1;35m %s \033[0m" % (sys.version[:7], sys.getdefaultencoding())) 12 13 # s = "字符編碼:尛" 14 s = "字符編碼:淼" 15 print("Original string : \033[1;35m %s \033[0m" % s) 16 17 s_to_unicode = s.decode("utf-8") # utf-8 is extended from unicode 18 print("utf-8 decode to the \033[1;33m unicode \033[0m type: \033[1;35m %s \033[0m" % s_to_unicode) 19 20 # 尛 doesn't in gb2312, it added in gbk 21 s_to_gb2312 = s_to_unicode.encode("gb2312") 22 print("unicode encode to the \033[1;35m gb2312 \033[0m type: \033[1;34m %s \033[0m" % s_to_gb2312) 23 24 s_to_unicode2 = s_to_gb2312.decode("gb2312") 25 print("gb2312 decode to the \033[1;35m unicode \033[0m type: \033[1;34m %s \033[0m" % s_to_unicode2) 26 27 s_to_gbk = s_to_unicode2.encode("gbk") 28 print("unicode encode to the \033[1;35m gbk \033[0m type: \033[1;34m %s \033[0m" % s_to_gbk) 29 30 s_backto_unicode = s_to_gbk.decode("gbk") 31 print("gbk encode to the \033[1;35m unicode \033[0m type: \033[1;34m %s \033[0m" % s_backto_unicode) 32 33 s_backto_utf8 = s_backto_unicode.encode("utf-8") 34 print("unicode decode to the \033[1;35m utf-8 \033[0m type: \033[1;34m %s \033[0m" % s_backto_utf8) 35 36 # End Of File
三、在Python3中,添加了bytes類型,將用戶輸入的字符編碼GBK、GB2312等,先轉換爲 bytes類型(decode),而後再轉換爲用戶想要的編碼(utf-8等)。
1 #!/usr/bin/python3.5 2 # -*- coding:utf-8 -*- 3 # encoding & decoding in Python3 4 # transfer from UTF-8 to GB2312, then to GBK; then Transfer back to UTF-8 5 # Spencer Jiang 6 # 2017-03-21 7 8 import sys 9 10 # default coding type in Python3 is utf-8 11 print("\nThe default coding type in \033[1;35m Python%s \033[0m is: \033[1;35m %s \033[0m" % (sys.version[:7], sys.getdefaultencoding())) 12 13 # s = "字符編碼:尛" 14 s = "字符編碼:淼" 15 print("Original string : \033[1;35m %s \033[0m" % s) 16 17 # 尛 doesn't in gb2312, it added in gbk 18 s_to_gb2312 = s.encode("gb2312") 19 print("utf8 encode to the \033[1;35m gb2312 (bytes) \033[0m type: \033[1;34m %s \033[0m" % s_to_gb2312) 20 21 s_to_unicode2 = s_to_gb2312.decode("gb2312") 22 print("gb2312 decode to the \033[1;35m unicode \033[0m type: \033[1;34m %s \033[0m" % s_to_unicode2) 23 24 s_to_gbk = s_to_unicode2.encode("gbk") 25 print("unicode encode to the \033[1;35m gbk (bytes) \033[0m type: \033[1;34m %s \033[0m" % s_to_gbk) 26 27 s_backto_unicode = s_to_gbk.decode("gbk") 28 print("gbk encode to the \033[1;35m unicode \033[0m type: \033[1;34m %s \033[0m" % s_backto_unicode) 29 30 s_backto_utf8 = s_backto_unicode.encode("utf-8") 31 print("unicode decode to the \033[1;35m utf-8 (bytes) \033[0m type: \033[1;34m %s \033[0m" % s_backto_utf8) 32 33 # End Of File
在Python中,函數以 def 關鍵字來進行定義:(根據PEP8規則,定義函數前面要有2行空行)
1 #!/usr/bin/python3.5 2 # -*- coding:utf-8 -*- 3 # Function: function invoke 4 # Author: Spencer J 5 # Date: 2017-03-24 6 7 8 # use 'def' to define a function 9 def func_hello(): 10 # print Hi 11 print("Hello, I am Spencer!") 12 13 # invoke the function name to execute 14 func_hello() 15 16 ------------ 執行結果 ---------- 17 Hello, I am Spencer!
函數能夠有返回值,也能夠沒有返回值;經過return關鍵字返回一個具體的值。對於有返回值的函數來講,函數結束於return語句。在return語句後的全部代碼都是無效的。
減小重複代碼; 可擴展; 易於維護。
1)形參: 形參只在函數內部有效,由於只有在調用到函數時纔會分配內存空間,在函數執行完成後即刻釋放。當有多個形參時,形參之間是有順序(位置)的(此時也可稱爲位置參數)。
2)實參: 在調用函數時,須要傳遞給函數的參數即爲實參。實參能夠是常量、變量、表達式、函數等任何類型的數據,可是在調用函數時實參的值必須是肯定的。
示例:下面定義一個求兩個數的和的函數func_sum(a, b)。 其中a和b就是形參,只在函數內有效; x 和y 就是實參,在調用函數傳遞給函數的形參。
1 # calculate the sum of 2 numbers 2 def func_sum(a, b): 3 print("a + b = %s + %s " % (a, b)) 4 # return the sum of a & b 5 return a + b 6 7 x = 12 8 y = 23 9 10 print(func_sum(x, y)) 11 print(a, b) # a, b only take effective in the func_sum() function 12 13 ------------------ 執行結果 ---------- 14 a + b = 12 + 23 15 35 16 Traceback (most recent call last): 17 File "/home/jmw/PycharmProjects/SpencerProjects/Day3/func_test1.py", line 18, in <module> 18 print(a, b) 19 NameError: name 'a' is not defined
3)默認參數:在定義函數時,能夠對某個形參指定默認的值,當調用函數時,能夠不傳實參給該形參,也能夠傳實參給該形參。此種函數通常用於軟件的默認安裝路徑及選項等。由於形參是有順序概念的,因此 默認參數必須在全部位置參數的後面。
在第2行定義函數時,將「install_dir」形參設置了一個默認的路徑; 在第13行中,只傳入一個參數給shortcut,不傳入install_dir參數,就打印默認的install_dir路徑;在第17行,傳入了兩個參數,就改變了install_dir的值。
1 # function parameters with a default value 2 def func_install_options(shortcut_pos, install_dir="c:/program file/python/"): 3 ''' 4 :param shortcut_pos: where you want to create a shortcut for the application 5 :param install_dir: where you want to install the application 6 :return: 7 ''' 8 print("Will create a shortcut on %s " % shortcut_pos) 9 print("Will be installed in %s " % install_dir) 10 11 print("default param".center(80, "*")) 12 # invoke function without pass a install_dir param 13 func_install_options("Desktop") 14 15 print("not default param".center(80, "*")) 16 # invoke function with a new install_dir param 17 func_install_options("Desktop", "c:/python/") 18 19 20 ----------------- 執行結果 ----------------- 21 *********************************default param********************************** 22 Will create a shortcut on Desktop 23 Will be installed in c:/program file/python/ 24 *******************************not default param******************************** 25 Will create a shortcut on Desktop 26 Will be installed in c:/python/
4)參數組|非固定參數:在定義函數時,形參的個數是不肯定的時候就能夠用參數組(也叫可變參數、非固定參數)。參數組通常用「*args」來定義,如 def func_test(a, b, *args), 能夠傳空。
1 # *args 2 def func_user_info(name, sex, *args): 3 print(name, sex, args) # args是個tuple 4 5 func_user_info("test", "boy", "23", "IT") 6 7 func_user_info("test", "boy") 8 9 10 ----------------------- 執行結果 --------------------------- 11 test boy ('23', 'IT') 12 test boy ()
當要傳入的非固定參數爲key-value對(字典)時,用「**kwargs」來定義,如 def_test(a, b=32, **kwargs)。
1 def func_dict2(name, **kwargs): 2 print(name, kwargs) 3 4 func_dict2("test") # **kwargs is {} 5 func_dict2("test", sex="boy", age=22) # **kwargs is {'sex': 'boy', 'age': 22} 6 7 func_dict2({'name': "alex", "sex": 1, "age": 22}) # name is {'name': "alex", "sex": 1, "age": 22}, **kwargs is {} 8 9 func_dict2(**{'name': "alex", "sex": 1, "age": 22}) # name is 'alex'; **kwargs is {'sex': 1, 'age': 22} 10 11 12 ------------------------ 執行結果 ------------------------- 13 test {} 14 test {'age': 22, 'sex': 'boy'} 15 {'age': 22, 'name': 'alex', 'sex': 1} {} 16 alex {'age': 22, 'sex': 1}
5)關鍵字參數:在調用函數時,傳遞實參給形參時,若是不想按順序,能夠指定形參名進行賦值傳遞參數,如 def func_test(a, b, c, d) 調用時func_test(b=1, c=3, d=123, a=2)
1 def func_print(x, y, z): 2 print("x = %s " % x) 3 print("y = %s " % y) 4 print("z = %s " % z) 5 6 print("**************************") 7 # 位置調用: 按參數的順序位置調用函數 8 func_print(1, 2, 3) # x=1, y=2, z=3 9 print("**************************") 10 # 關鍵字調用: 按參數名賦值後進行調用 11 func_print(y=3, x=2, z=1) # x=2, y=3, z=1 12 print("**************************") 13 # 位置調用 + 關鍵字調用: 14 func_print(1, z=5, y=2) # x=1, y=2, z=5 15 print("**************************") 16 # 關鍵字調用 + 位置調用:關鍵字調用後不能放在位置調用前。 17 # func_print(x=3, 2, z=1) # SyntaxError: positional argument follows keyword argument 18 19 20 -------------------------- 執行結果 -------------------------------- 21 ************************** 22 x = 1 23 y = 2 24 z = 3 25 ************************** 26 x = 2 27 y = 3 28 z = 1 29 ************************** 30 x = 1 31 y = 2 32 z = 5 33 **************************
1)局部變量: 在子程序裏面(函數裏)定義的變量,只在函數體內(子程序裏)起做用。
2)全局變量: 在程序開頭定義的變量,在整個程序中都起做用。
# 全局變量 user_name = "spencer" def func_var(name, age): user_name = 'John Spencer' # 與全局變量同名 print(user_name) # 局部變量 print(name, age) _user_name = "jmw" # 局部變量 print(_user_name) func_var(user_name, 23) print(user_name) ------------------------ 執行結果 ------------------ John Spencer spencer 23 jmw spencer
當全局變量與局部變量同名時:在定義局部變量的子程序內,局部變量起做用【局部變量要先定義,而後才能再引用,不然會報「UnboundLocalError: local variable 'user_name' referenced before assignment」錯誤】;在其它地方全局變量起做用。
一個函數能夠調用另一個函數,也能夠調用函數自己,就變成一個遞歸函數。遞歸函數通常用於數學運算,如斐波拉契數列(示例代碼)等。遞歸函數有如下特性:
1)有明確的結束遞歸的條件。
2)在每次遞歸後,遞歸的規模就縮小。
3) 遞歸層次要儘可能少。由於遞歸的效率低下,遞歸層次太多容易致使棧溢出。
1 # fibonacci--an = a(n-1) + a(n-2): a0=0, a1=0, a2=1, a3=2, a4=5... 2 def fibonacci(n): 3 if n > 1: 4 return fibonacci(n-1) + fibonacci(n-2) 5 elif n == 1: 6 return 1 7 elif n == 0: 8 return 0 9 10 for i in range(10): 11 print(fibonacci(i)) 12 13 --------------------- 執行結果 ------------------- 14 0 15 1 16 1 17 2 18 3 19 5 20 8 21 13 22 21 23 34
函數式編程主要是將代碼變成調用一系列函數的過程(嵌套的函數調用過程)。可能經過這篇文章瞭解函數式編程。
python如今也支持函數式編程(lambda,面向對象的編程語言,如C#,也是經過lambda來實現函數式編程)。
本週做業:
HAproxy配置文件操做:配置文件內容參考 http://www.cnblogs.com/alex3714/articles/5717620.html
1. 根據用戶輸入輸出對應的backend下的server信息
2. 可添加backend 和sever信息
3. 可修改backend 和sever信息
4. 可刪除backend 和sever信息
5. 操做配置文件前進行備份
6 添加server信息時,若是ip已經存在則修改;若是backend不存在則建立;若信息與已有信息重複則不操做