Python开发【第六篇】:模块
模塊,用一砣代碼實現了某個功能的代碼集合。?
類似于函數式編程和面向過程編程,函數式編程則完成一個功能,其他代碼用來調用即可,提供了代碼的重用性和代碼間的耦合。而對于一個復雜的功能來,可能需要多個函數才能完成(函數又可以在不同的.py文件中),n個 .py 文件組成的代碼集合就稱為模塊。
如:os 是系統相關的模塊;file是文件操作相關的模塊
模塊分為三種:
- 自定義模塊
- 第三方模塊
- 內置模塊
自定義模塊
1、定義模塊
情景一:
情景二:
情景三:
2、導入模塊
Python之所以應用越來越廣泛,在一定程度上也依賴于其為程序員提供了大量的模塊以供使用,如果想要使用模塊,則需要導入。導入模塊有一下幾種方法:
| 1 2 3 4 | import?module from?module.xx.xx?import?xx from?module.xx.xx?import?xx as rename? from?module.xx.xx?import?* |
導入模塊其實就是告訴Python解釋器去解釋那個py文件
- 導入一個py文件,解釋器解釋該py文件
- 導入一個包,解釋器解釋該包下的 __init__.py 文件 【py2.7】
那么問題來了,導入模塊時是根據那個路徑作為基準來進行的呢?即:sys.path
| 1 2 3 4 5 | import?sys print?sys.path ??? 結果: ['/Users/wupeiqi/PycharmProjects/calculator/p1/pp1',?'/usr/local/lib/python2.7/site-packages/setuptools-15.2-py2.7.egg',?'/usr/local/lib/python2.7/site-packages/distribute-0.6.28-py2.7.egg',?'/usr/local/lib/python2.7/site-packages/MySQL_python-1.2.4b4-py2.7-macosx-10.10-x86_64.egg',?'/usr/local/lib/python2.7/site-packages/xlutils-1.7.1-py2.7.egg',?'/usr/local/lib/python2.7/site-packages/xlwt-1.0.0-py2.7.egg',?'/usr/local/lib/python2.7/site-packages/xlrd-0.9.3-py2.7.egg',?'/usr/local/lib/python2.7/site-packages/tornado-4.1-py2.7-macosx-10.10-x86_64.egg',?'/usr/local/lib/python2.7/site-packages/backports.ssl_match_hostname-3.4.0.2-py2.7.egg',?'/usr/local/lib/python2.7/site-packages/certifi-2015.4.28-py2.7.egg',?'/usr/local/lib/python2.7/site-packages/pyOpenSSL-0.15.1-py2.7.egg',?'/usr/local/lib/python2.7/site-packages/six-1.9.0-py2.7.egg',?'/usr/local/lib/python2.7/site-packages/cryptography-0.9.1-py2.7-macosx-10.10-x86_64.egg',?'/usr/local/lib/python2.7/site-packages/cffi-1.1.1-py2.7-macosx-10.10-x86_64.egg',?'/usr/local/lib/python2.7/site-packages/ipaddress-1.0.7-py2.7.egg',?'/usr/local/lib/python2.7/site-packages/enum34-1.0.4-py2.7.egg',?'/usr/local/lib/python2.7/site-packages/pyasn1-0.1.7-py2.7.egg',?'/usr/local/lib/python2.7/site-packages/idna-2.0-py2.7.egg',?'/usr/local/lib/python2.7/site-packages/pycparser-2.13-py2.7.egg',?'/usr/local/lib/python2.7/site-packages/Django-1.7.8-py2.7.egg',?'/usr/local/lib/python2.7/site-packages/paramiko-1.10.1-py2.7.egg',?'/usr/local/lib/python2.7/site-packages/gevent-1.0.2-py2.7-macosx-10.10-x86_64.egg',?'/usr/local/lib/python2.7/site-packages/greenlet-0.4.7-py2.7-macosx-10.10-x86_64.egg',?'/Users/wupeiqi/PycharmProjects/calculator',?'/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python27.zip',?'/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7',?'/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',?'/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',?'/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',?'/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',?'/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old',?'/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload',?'/usr/local/lib/python2.7/site-packages',?'/Library/Python/2.7/site-packages'] |
如果sys.path路徑列表沒有你想要的路徑,可以通過 sys.path.append('路徑') 添加。
| 1 2 3 4 | import?sys import?os project_path?=?os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(project_path) |
模塊
內置模塊是Python自帶的功能,在使用內置模塊相應的功能時,需要【先導入】再【使用】
一、sys
用于提供對Python解釋器相關的操作:
| 1 2 3 4 5 6 7 8 9 | sys.argv?????????? 命令行參數List,第一個元素是程序本身路徑 sys.exit(n)??????? 退出程序,正常退出時exit(0) sys.version??????? 獲取Python解釋程序的版本信息 sys.maxint???????? 最大的Int值 sys.path?????????? 返回模塊的搜索路徑,初始化時使用PYTHONPATH環境變量的值 sys.platform?????? 返回操作系統平臺名稱 sys.stdin????????? 輸入相關 sys.stdout???????? 輸出相關 sys.stderror?????? 錯誤相關 |
二、os
用于提供系統級別的操作:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | os.getcwd()???????????????? 獲取當前工作目錄,即當前python腳本工作的目錄路徑 os.chdir("dirname")???????? 改變當前腳本工作目錄;相當于shell下cd os.curdir?????????????????? 返回當前目錄: ('.') os.pardir?????????????????? 獲取當前目錄的父目錄字符串名:('..') os.makedirs('dir1/dir2')??? 可生成多層遞歸目錄 os.removedirs('dirname1')?? 若目錄為空,則刪除,并遞歸到上一級目錄,如若也為空,則刪除,依此類推 os.mkdir('dirname')???????? 生成單級目錄;相當于shell中mkdir dirname os.rmdir('dirname')???????? 刪除單級空目錄,若目錄不為空則無法刪除,報錯;相當于shell中rmdir dirname os.listdir('dirname')?????? 列出指定目錄下的所有文件和子目錄,包括隱藏文件,并以列表方式打印 os.remove()???????????????? 刪除一個文件 os.rename("oldname","new")? 重命名文件/目錄 os.stat('path/filename')??? 獲取文件/目錄信息 os.sep????????????????????? 操作系統特定的路徑分隔符,win下為"\\",Linux下為"/" os.linesep????????????????? 當前平臺使用的行終止符,win下為"\t\n",Linux下為"\n" os.pathsep????????????????? 用于分割文件路徑的字符串 os.name???????????????????? 字符串指示當前使用平臺。win->'nt'; Linux->'posix' os.system("bash command")?? 運行shell命令,直接顯示 os.environ????????????????? 獲取系統環境變量 os.path.abspath(path)?????? 返回path規范化的絕對路徑 os.path.split(path)???????? 將path分割成目錄和文件名二元組返回 os.path.dirname(path)?????? 返回path的目錄。其實就是os.path.split(path)的第一個元素 os.path.basename(path)????? 返回path最后的文件名。如何path以/或\結尾,那么就會返回空值。即os.path.split(path)的第二個元素 os.path.exists(path)??????? 如果path存在,返回True;如果path不存在,返回False os.path.isabs(path)???????? 如果path是絕對路徑,返回True os.path.isfile(path)??????? 如果path是一個存在的文件,返回True。否則返回False os.path.isdir(path)???????? 如果path是一個存在的目錄,則返回True。否則返回False os.path.join(path1[, path2[, ...]])? 將多個路徑組合后返回,第一個絕對路徑之前的參數將被忽略 os.path.getatime(path)????? 返回path所指向的文件或者目錄的最后存取時間 os.path.getmtime(path)????? 返回path所指向的文件或者目錄的最后修改時間 |
三、hashlib
用于加密相關的操作,代替了md5模塊和sha模塊,主要提供?SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | import?hashlib # ######## md5 ######## hash?=?hashlib.md5() # help(hash.update) hash.update(bytes('admin', encoding='utf-8')) print(hash.hexdigest()) print(hash.digest()) ######## sha1 ######## hash?=?hashlib.sha1() hash.update(bytes('admin', encoding='utf-8')) print(hash.hexdigest()) # ######## sha256 ######## hash?=?hashlib.sha256() hash.update(bytes('admin', encoding='utf-8')) print(hash.hexdigest()) # ######## sha384 ######## hash?=?hashlib.sha384() hash.update(bytes('admin', encoding='utf-8')) print(hash.hexdigest()) # ######## sha512 ######## hash?=?hashlib.sha512() hash.update(bytes('admin', encoding='utf-8')) print(hash.hexdigest()) |
以上加密算法雖然依然非常厲害,但時候存在缺陷,即:通過撞庫可以反解。所以,有必要對加密算法中添加自定義key再來做加密。
| 1 2 3 4 5 6 7 | import?hashlib # ######## md5 ######## hash?=?hashlib.md5(bytes('898oaFs09f',encoding="utf-8")) hash.update(bytes('admin',encoding="utf-8")) print(hash.hexdigest()) |
python內置還有一個 hmac 模塊,它內部對我們創建 key 和 內容 進行進一步的處理然后再加密
| 1 2 3 4 5 | import?hmac h?=?hmac.new(bytes('898oaFs09f',encoding="utf-8")) h.update(bytes('admin',encoding="utf-8")) print(h.hexdigest()) |
四、random
| 1 2 3 4 5 | import?random print(random.random()) print(random.randint(1,?2)) print(random.randrange(1,?10)) |
五、re
python中re模塊提供了正則表達式相關操作
?
字符:
?
. 匹配除換行符以外的任意字符
\w 匹配字母或數字或下劃線或漢字
\s 匹配任意的空白符
\d 匹配數字
\b 匹配單詞的開始或結束
^ 匹配字符串的開始
$ 匹配字符串的結束
?
次數:
?
* 重復零次或更多次
+ 重復一次或更多次
? 重復零次或一次
{n} 重復n次
{n,} 重復n次或更多次
{n,m} 重復n到m次
?
match
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | # match,從起始位置開始匹配,匹配成功返回一個對象,未匹配成功返回None ?match(pattern, string, flags=0) ?# pattern: 正則模型 ?# string : 要匹配的字符串 ?# falgs? : 匹配模式 ?????X? VERBOSE???? Ignore whitespace?and?comments?for?nicer looking RE's. ?????I? IGNORECASE? Perform case-insensitive matching. ?????M? MULTILINE???"^"?matches the beginning of lines (after a newline) ????????????????????as well as the string. ????????????????????"$"?matches the end of lines (before a newline) as well ????????????????????as the end of the string. ?????S? DOTALL??????"."?matches?any?character at?all, including the newline. ?????A? ASCII?????? For string patterns, make \w, \W, \b, \B, \d, \D ????????????????????match the corresponding ASCII character categories ????????????????????(rather than the whole?Unicode?categories, which?is?the ????????????????????default). ????????????????????For bytes patterns, this flag?is?the only available ????????????????????behaviour?and?needn't be specified. ?????? ?????L? LOCALE????? Make \w, \W, \b, \B, dependent on the current locale. ?????U??UNICODE?????For compatibility only. Ignored?for?string patterns (it ????????????????????is?the default),?and?forbidden?for?bytes patterns. |
search
| 1 2 | # search,瀏覽整個字符串去匹配第一個,未匹配成功返回None # search(pattern, string, flags=0) |
findall
| 1 2 3 | # findall,獲取非重復的匹配列表;如果有一個組則以列表形式返回,且每一個匹配均是字符串;如果模型中有多個組,則以列表形式返回,且每一個匹配均是元祖; # 空的匹配也會包含在結果中 #findall(pattern, string, flags=0) |
sub
| 1 2 3 4 5 6 7 8 | # sub,替換匹配成功的指定位置字符串 sub(pattern, repl, string, count=0, flags=0) # pattern: 正則模型 # repl?? : 要替換的字符串或可執行對象 # string : 要匹配的字符串 # count? : 指定匹配個數 # flags? : 匹配模式 |
split
| 1 2 3 4 5 6 7 | # split,根據正則匹配分割字符串 split(pattern, string, maxsplit=0, flags=0) # pattern: 正則模型 # string : 要匹配的字符串 # maxsplit:指定分割個數 # flags? : 匹配模式 |
六、序列化
Python中用于序列化的兩個模塊
- json ? ? 用于【字符串】和 【python基本數據類型】 間進行轉換
- pickle ? 用于【python特有的類型】 和 【python基本數據類型】間進行轉換
Json模塊提供了四個功能:dumps、dump、loads、load
pickle模塊提供了四個功能:dumps、dump、loads、load
?
七、configparser
configparser用于處理特定格式的文件,其本質上是利用open來操作文件。
?指定格式1、獲取所有節點
| 1 2 3 4 5 6 | import?configparser config?=?configparser.ConfigParser() config.read('xxxooo', encoding='utf-8') ret?=?config.sections() print(ret) |
2、獲取指定節點下所有的鍵值對
| 1 2 3 4 5 6 | import?configparser config?=?configparser.ConfigParser() config.read('xxxooo', encoding='utf-8') ret?=?config.items('section1') print(ret) |
3、獲取指定節點下所有的建
| 1 2 3 4 5 6 | import?configparser config?=?configparser.ConfigParser() config.read('xxxooo', encoding='utf-8') ret?=?config.options('section1') print(ret) |
4、獲取指定節點下指定key的值
| 1 2 3 4 5 6 7 8 9 10 11 12 | import?configparser config?=?configparser.ConfigParser() config.read('xxxooo', encoding='utf-8') v?=?config.get('section1',?'k1') # v = config.getint('section1', 'k1') # v = config.getfloat('section1', 'k1') # v = config.getboolean('section1', 'k1') print(v) |
5、檢查、刪除、添加節點
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import?configparser config?=?configparser.ConfigParser() config.read('xxxooo', encoding='utf-8') # 檢查 has_sec?=?config.has_section('section1') print(has_sec) # 添加節點 config.add_section("SEC_1") config.write(open('xxxooo',?'w')) # 刪除節點 config.remove_section("SEC_1") config.write(open('xxxooo',?'w')) |
6、檢查、刪除、設置指定組內的鍵值對
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import?configparser config?=?configparser.ConfigParser() config.read('xxxooo', encoding='utf-8') # 檢查 has_opt?=?config.has_option('section1',?'k1') print(has_opt) # 刪除 config.remove_option('section1',?'k1') config.write(open('xxxooo',?'w')) # 設置 config.set('section1',?'k10',?"123") config.write(open('xxxooo',?'w')) |
八、XML
XML是實現不同語言或程序之間進行數據交換的協議,XML文件格式如下:
<data><country name="Liechtenstein"><rank updated="yes">2</rank><year>2023</year><gdppc>141100</gdppc><neighbor direction="E" name="Austria" /><neighbor direction="W" name="Switzerland" /></country><country name="Singapore"><rank updated="yes">5</rank><year>2026</year><gdppc>59900</gdppc><neighbor direction="N" name="Malaysia" /></country><country name="Panama"><rank updated="yes">69</rank><year>2026</year><gdppc>13600</gdppc><neighbor direction="W" name="Costa Rica" /><neighbor direction="E" name="Colombia" /></country> </data>1、解析XML
?利用ElementTree.XML將字符串解析成xml對象 ?利用ElementTree.parse將文件直接解析成xml對象2、操作XML
XML格式類型是節點嵌套節點,對于每一個節點均有以下功能,以便對當前節點進行操作:
?節點功能一覽表由于 每個節點 都具有以上的方法,并且在上一步驟中解析時均得到了root(xml文件的根節點),so ? 可以利用以上方法進行操作xml文件。
a.?遍歷XML文檔的所有內容
?View Codeb、遍歷XML中指定的節點
?View Codec、修改節點內容
由于修改的節點時,均是在內存中進行,其不會影響文件中的內容。所以,如果想要修改,則需要重新將內存中的內容寫到文件。
?解析字符串方式,修改,保存 ?解析文件方式,修改,保存d、刪除節點
?解析字符串方式打開,刪除,保存 ?解析文件方式打開,刪除,保存3、創建XML文檔
?創建方式(一) ?創建方式(二) ?創建方式(三)由于原生保存的XML時默認無縮進,如果想要設置縮進的話, 需要修改保存方式:
?View Code4、命名空間
詳細介紹,猛擊這里
?命名空間九、requests
Python標準庫中提供了:urllib等模塊以供Http請求,但是,它的 API 太渣了。它是為另一個時代、另一個互聯網所創建的。它需要巨量的工作,甚至包括各種方法覆蓋,來完成最簡單的任務。
?發送GET請求 ?發送攜帶請求頭的GET請求注:更多見Python官方文檔:https://docs.python.org/3.5/library/urllib.request.html#module-urllib.request
Requests 是使用 Apache2 Licensed 許可證的 基于Python開發的HTTP 庫,其在Python內置模塊的基礎上進行了高度的封裝,從而使得Pythoner進行網絡請求時,變得美好了許多,使用Requests可以輕而易舉的完成瀏覽器可有的任何操作。
1、安裝模塊
| 1 | pip3 install requests |
2、使用模塊
?GET請求 ?POST請求 ?其他請求更多requests模塊相關的文檔見:http://cn.python-requests.org/zh_CN/latest/
3、Http請求和XML實例
實例:檢測QQ賬號是否在線
?View Code實例:查看火車停靠信息
?View Code注:更多接口猛擊這里
十、logging
用于便捷記錄日志且線程安全的模塊
1、單文件日志
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import?logging ?? ?? logging.basicConfig(filename='log.log', ????????????????????format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:? %(message)s', ????????????????????datefmt='%Y-%m-%d %H:%M:%S %p', ????????????????????level=10) ?? logging.debug('debug') logging.info('info') logging.warning('warning') logging.error('error') logging.critical('critical') logging.log(10,'log') |
日志等級:
CRITICAL = 50 FATAL = CRITICAL ERROR = 40 WARNING = 30 WARN = WARNING INFO = 20 DEBUG = 10 NOTSET = 0注:只有【當前寫等級】大于【日志等級】時,日志文件才被記錄。
日志記錄格式:
2、多文件日志
對于上述記錄日志的功能,只能將日志記錄在單文件中,如果想要設置多個日志文件,logging.basicConfig將無法完成,需要自定義文件和日志操作對象。
?日志一 ?日志(二)如上述創建的兩個日志對象
- 當使用【logger1】寫日志時,會將相應的內容寫入 l1_1.log 和 l1_2.log 文件中
- 當使用【logger2】寫日志時,會將相應的內容寫入 l2_1.log 文件中
十一、系統命令
可以執行shell命令的相關模塊和函數有:
- os.system
- os.spawn*
- os.popen* ? ? ? ? ?--廢棄
- popen2.* ? ? ? ? ? --廢棄
- commands.* ? ? ?--廢棄,3.x中被移除
以上執行shell命令的相關的模塊和函數的功能均在 subprocess 模塊中實現,并提供了更豐富的功能。
call?
執行命令,返回狀態碼
| 1 2 | ret?=?subprocess.call(["ls",?"-l"], shell=False) ret?=?subprocess.call("ls -l", shell=True) |
check_call
執行命令,如果執行狀態碼是 0 ,則返回0,否則拋異常
| 1 2 | subprocess.check_call(["ls",?"-l"]) subprocess.check_call("exit 1", shell=True) |
check_output
執行命令,如果狀態碼是 0 ,則返回執行結果,否則拋異常
| 1 2 | subprocess.check_output(["echo",?"Hello World!"]) subprocess.check_output("exit 1", shell=True) |
subprocess.Popen(...)
用于執行復雜的系統命令
參數:
- args:shell命令,可以是字符串或者序列類型(如:list,元組)
- bufsize:指定緩沖。0 無緩沖,1 行緩沖,其他 緩沖區大小,負值 系統緩沖
- stdin, stdout, stderr:分別表示程序的標準輸入、輸出、錯誤句柄
- preexec_fn:只在Unix平臺下有效,用于指定一個可執行對象(callable object),它將在子進程運行之前被調用
- close_sfs:在windows平臺下,如果close_fds被設置為True,則新創建的子進程將不會繼承父進程的輸入、輸出、錯誤管道。
所以不能將close_fds設置為True同時重定向子進程的標準輸入、輸出與錯誤(stdin, stdout, stderr)。 - shell:同上
- cwd:用于設置子進程的當前目錄
- env:用于指定子進程的環境變量。如果env = None,子進程的環境變量將從父進程中繼承。
- universal_newlines:不同系統的換行符不同,True -> 同意使用 \n
- startupinfo與createionflags只在windows下有效
將被傳遞給底層的CreateProcess()函數,用于設置子進程的一些屬性,如:主窗口的外觀,進程的優先級等等?
終端輸入的命令分為兩種:
- 輸入即可得到輸出,如:ifconfig
- 輸入進行某環境,依賴再輸入,如:python
十二、shutil
高級的 文件、文件夾、壓縮包 處理模塊
shutil.copyfileobj(fsrc, fdst[, length])
將文件內容拷貝到另一個文件中
| 1 2 3 | import?shutil shutil.copyfileobj(open('old.xml','r'),?open('new.xml',?'w')) |
shutil.copyfile(src, dst)
拷貝文件
| 1 | shutil.copyfile('f1.log',?'f2.log') |
shutil.copymode(src, dst)
僅拷貝權限。內容、組、用戶均不變
| 1 | shutil.copymode('f1.log',?'f2.log') |
shutil.copystat(src, dst)
僅拷貝狀態的信息,包括:mode bits, atime, mtime, flags
| 1 | shutil.copystat('f1.log',?'f2.log') |
shutil.copy(src, dst)
拷貝文件和權限
| 1 2 3 | import?shutil shutil.copy('f1.log',?'f2.log') |
shutil.copy2(src, dst)
拷貝文件和狀態信息
| 1 2 3 | import?shutil shutil.copy2('f1.log',?'f2.log') |
shutil.ignore_patterns(*patterns)
shutil.copytree(src, dst, symlinks=False, ignore=None)
遞歸的去拷貝文件夾
| 1 2 3 | import?shutil shutil.copytree('folder1',?'folder2', ignore=shutil.ignore_patterns('*.pyc',?'tmp*')) |
shutil.rmtree(path[, ignore_errors[, onerror]])
遞歸的去刪除文件
| 1 2 3 | import?shutil shutil.rmtree('folder1') |
shutil.move(src, dst)
遞歸的去移動文件,它類似mv命令,其實就是重命名。
| 1 2 3 | import?shutil shutil.move('folder1',?'folder3') |
shutil.make_archive(base_name, format,...)
創建壓縮包并返回文件路徑,例如:zip、tar
創建壓縮包并返回文件路徑,例如:zip、tar
- base_name: 壓縮包的文件名,也可以是壓縮包的路徑。只是文件名時,則保存至當前目錄,否則保存至指定路徑,
如:www ? ? ? ? ? ? ? ? ? ? ? ?=>保存至當前路徑
如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/ - format: 壓縮包種類,“zip”, “tar”, “bztar”,“gztar”
- root_dir: 要壓縮的文件夾路徑(默認當前目錄)
- owner: 用戶,默認當前用戶
- group: 組,默認當前組
- logger: 用于記錄日志,通常是logging.Logger對象
| 1 2 3 4 5 6 7 8 | #將 /Users/wupeiqi/Downloads/test 下的文件打包放置當前程序目錄 import?shutil ret?=?shutil.make_archive("wwwwwwwwww",?'gztar', root_dir='/Users/wupeiqi/Downloads/test') ?? ?? #將 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目錄 import?shutil ret?=?shutil.make_archive("/Users/wupeiqi/wwwwwwwwww",?'gztar', root_dir='/Users/wupeiqi/Downloads/test') |
shutil 對壓縮包的處理是調用 ZipFile 和 TarFile 兩個模塊來進行的,詳細:
?zipfile解壓縮 ?tarfile解壓縮十三、paramiko
paramiko是一個用于做遠程控制的模塊,使用該模塊可以對遠程服務器進行命令或文件操作,值得一說的是,fabric和ansible內部的遠程管理就是使用的paramiko來現實。
1、下載安裝
| 1 2 3 | pycrypto,由于 paramiko 模塊內部依賴pycrypto,所以先下載安裝pycrypto pip3 install pycrypto pip3 install paramiko |
2、模塊使用
?執行命令 - 用戶名+密碼 ?執行命令 - 密鑰 ?上傳或下載文件 - 用戶名+密碼 ?上傳或下載文件 - 密鑰十四、time
時間相關的操作,時間有三種表示方式:
- 時間戳 ? ? ? ? ? ? ? 1970年1月1日之后的秒,即:time.time()
- 格式化的字符串 ? ?2014-11-11 11:11, ? ?即:time.strftime('%Y-%m-%d')
- 結構化時間 ? ? ? ? ?元組包含了:年、日、星期等... time.struct_time ? ?即:time.localtime()
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | print?time.time() print?time.mktime(time.localtime()) ??? print?time.gmtime()????#可加時間戳參數 print?time.localtime()?#可加時間戳參數 print?time.strptime('2014-11-11',?'%Y-%m-%d') ??? print?time.strftime('%Y-%m-%d')?#默認當前時間 print?time.strftime('%Y-%m-%d',time.localtime())?#默認當前時間 print?time.asctime() print?time.asctime(time.localtime()) print?time.ctime(time.time()) ??? import?datetime ''' datetime.date:表示日期的類。常用的屬性有year, month, day datetime.time:表示時間的類。常用的屬性有hour, minute, second, microsecond datetime.datetime:表示日期時間 datetime.timedelta:表示時間間隔,即兩個時間點之間的長度 timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]]) strftime("%Y-%m-%d") ''' import?datetime print?datetime.datetime.now() print?datetime.datetime.now()?-?datetime.timedelta(days=5) |
?
練習題:
1、通過HTTP請求和XML實現獲取電視節目
? ? ?API:http://www.webxml.com.cn/webservices/ChinaTVprogramWebService.asmx??
2、通過HTTP請求和JSON實現獲取天氣狀況
? ? ?API:http://wthrcdn.etouch.cn/weather_mini?city=北京
posted on 2019-04-11 17:32 恒笛 閱讀(...) 評論(...) 編輯 收藏轉載于:https://www.cnblogs.com/xwqhl/p/10691104.html
總結
以上是生活随笔為你收集整理的Python开发【第六篇】:模块的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [Swift]LeetCode281.
- 下一篇: CMS垃圾收集器