python模塊的導入以及模塊簡介


一、模塊的定義及類型

1、定義

模塊就是用一堆的代碼實現了一些功能的代碼的集合,通常一個或者多個函數寫在一個.py文件里,而如果有些功能實現起來很復雜,那么就需要創建n個.py文件,這n個.py文件的集合就是模塊

2、類型

1)自定義模塊,自己寫的實現自己某些功能需求的.py文件集合

2)導入的模塊

在你安裝python之后,它自己內部的lib文件下就有很多模塊可以用,導入后就可以使用,通常路徑是C:\Python27\Lib   (27是版本號,如果是3.5的版本就是C:\Python35\Lib)

3)第三方開源模塊

第三方開源模塊通常需要自己去下載,這里以linux和windows系統為例子說明

linux系統

 1 # 下載安裝 pycrypto
 2 
 3 wget http://files.cnblogs.com/files/wupeiqi/pycrypto-2.6.1.tar.gz
 4 
 5 tar -xvf pycrypto-2.6.1.tar.gz
 6 
 7 cd pycrypto-2.6.1
 8 
 9 python setup.py build
10 
11 python setup.py install
View Code
1 #注:在使用源碼安裝時,需要使用到gcc編譯和python開發環境,所以,需要先執行
2 
3 yum install gcc
4 
5 yum install python-devel
6 或者
7 apt-get python-dev 

安裝成功后,模塊會自動安裝到 sys.path 中的某個目錄中,如/usr/lib/python3.5/site-packages

windows系統

1.源碼安裝

1.設置python的環境變量
A.控制面板-系統和安全-系統-高級系統設置-環境變量-系統變量-path
B.將python安裝目錄添加到里面,我的是C:\Python35
2.到網上下載你需要的模塊,並解壓,里面有setup.py文件
3.打開Cmd(命令提示符),切換到解壓模塊的目錄
4.運行命令:1、setup.py build --> 2、setup.py install
5.重新打開python IDE, import xxx (模塊名稱 ),沒報錯則安裝成功

2.用pip3安裝

或者直接切換到 C:\Python35\Lib\site-packages目錄下安裝
用pip3 install xxx(要安裝的模塊名稱)然后它就會自己下載了,很簡單

  

二、python的模塊的導入方式

#主要包括以下幾種導入方式:

1、import moduels(模塊名字)   #導入整個模塊,這種導入方式比較占用內存

2、import moduels (模塊名字)  as  XX             #這里是導入整個模塊的同時給它取一個別名,因為有些模塊名字比較長,用一個縮寫的別名代替在下次用到它時就比較方便

3、from modules(模塊名字)  import func(方法)     #從一個模塊里導入方法,你要用到模塊里的什么方法就從那個模塊里導入那個方法,這樣占用的內存就比較少

也可以用別名表示 : from modules(模塊名字)  import func(方法)as   XX

4、from package.modules   import func(方法)     #從一個包的模塊里導入方法 這個方法跟上面那種基本一樣,占用的內存也比較少

也可以用別名表示,from modules(模塊名字)  import func(方法)as   XX

  

導入模塊其實就是告訴Python解釋器去解釋那個py文件

導入一個py文件,解釋器解釋該py文件
導入一個包,解釋器解釋該包下的 __init__.py 文件

  

 模塊導入的路徑是以什么為標准的呢,就是以sys.path來查看

1 >>> import sys
2 >>> print(sys.path)
3 ['', 'C:\\Users\\shaopeng\\AppData\\Local\\Programs\\Python\\Python35\\Lib\\idlelib', 

'C:\\Users\\shaopeng\\AppData\\Local\\Programs\\Python\\Python35\\python35.zip',
'C:\\Users\\shaopeng\\AppData\\Local\\Programs\\Python\\Python35\\DLLs',
'C:\\Users\\shaopeng\\AppData\\Local\\Programs\\Python\\Python35\\lib',
'C:\\Users\\shaopeng\\AppData\\Local\\Programs\\Python\\Python35',
'C:\\Users\\shaopeng\\AppData\\Local\\Programs\\Python\\Python35\\lib\\site-packages']

如果你要導入的模塊不在這些路徑下面,你就可以用sys.path.append('你要導入的絕對路徑')

三、python當中用到的模塊不少,這里介紹一些常用的模塊

os 模塊

 1 os.getcwd() 獲取當前工作目錄,即當前python腳本工作的目錄路徑
 2 os.chdir("dirname")  改變當前腳本工作目錄;相當於shell下cd
 3 os.curdir  返回當前目錄: ('.')
 4 os.pardir  獲取當前目錄的父目錄字符串名:('..')
 5 os.makedirs('dirname1/dirname2')    可生成多層遞歸目錄
 6 os.removedirs('dirname1')    若目錄為空,則刪除,並遞歸到上一級目錄,如若也為空,則刪除,依此類推
 7 os.mkdir('dirname')    生成單級目錄;相當於shell中mkdir dirname
 8 os.rmdir('dirname')    刪除單級空目錄,若目錄不為空則無法刪除,報錯;相當於shell中rmdir dirname
 9 os.listdir('dirname')    列出指定目錄下的所有文件和子目錄,包括隱藏文件,並以列表方式打印
10 os.remove()  刪除一個文件
11 os.rename("oldname","newname")  重命名文件/目錄
12 os.stat('path/filename')  獲取文件/目錄信息
13 os.sep    輸出操作系統特定的路徑分隔符,win下為"\\",Linux下為"/"
14 os.linesep    輸出當前平台使用的行終止符,win下為"\t\n",Linux下為"\n"
15 os.pathsep    輸出用於分割文件路徑的字符串
16 os.name    輸出字符串指示當前使用平台。win->'nt'; Linux->'posix'
17 os.system("bash command")  運行shell命令,直接顯示
18 os.environ  獲取系統環境變量
19 os.path.abspath(path)  返回path規范化的絕對路徑
20 os.path.split(path)  將path分割成目錄和文件名二元組返回
21 os.path.dirname(path)  返回path的目錄。其實就是os.path.split(path)的第一個元素
22 os.path.basename(path)  返回path最后的文件名。如何path以/或\結尾,那么就會返回空值。即os.path.split(path)的第二個元素
23 os.path.exists(path)  如果path存在,返回True;如果path不存在,返回False
24 os.path.isabs(path)  如果path是絕對路徑,返回True
25 os.path.isfile(path)  如果path是一個存在的文件,返回True。否則返回False
26 os.path.isdir(path)  如果path是一個存在的目錄,則返回True。否則返回False
27 os.path.join(path1[, path2[, ...]])  將多個路徑組合后返回,第一個絕對路徑之前的參數將被忽略
28 os.path.getatime(path)  返回path所指向的文件或者目錄的最后存取時間
29 os.path.getmtime(path)  返回path所指向的文件或者目錄的最后修改時間
View Code

sys 模塊

用於提供對解釋器相關的操作

1 sys.argv           命令行參數List,第一個元素是程序本身路徑
2 sys.exit(n)        退出程序,正常退出時exit(0)
3 sys.version        獲取Python解釋程序的版本信息
4 sys.maxint         最大的Int值
5 sys.path           返回模塊的搜索路徑,初始化時使用PYTHONPATH環境變量的值
6 sys.platform       返回操作系統平台名稱
7 sys.stdout.write('please:')
8 val = sys.stdin.readline()[:-1]
View Code

hashlib 模塊

 1 import hashlib
 2 
 3  
 4 
 5 # ######## md5 ########
 6 
 7  
 8 
 9 hash = hashlib.md5()
10 
11 hash.update('admin')
12 
13 print hash.hexdigest()
14 
15  
16 
17 # ######## sha1 ########
18 
19  
20 
21 hash = hashlib.sha1()
22 
23 hash.update('admin')
24 
25 print hash.hexdigest()
26 
27  
28 
29 # ######## sha256 ########
30 
31  
32 
33 hash = hashlib.sha256()
34 
35 hash.update('admin')
36 
37 print hash.hexdigest()
38 
39  
40 
41  
42 
43 # ######## sha384 ########
44 
45  
46 
47 hash = hashlib.sha384()
48 
49 hash.update('admin')
50 
51 print hash.hexdigest()
52 
53  
54 
55 # ######## sha512 ########
56 
57  
58 
59 hash = hashlib.sha512()
60 
61 hash.update('admin')
62 
63 print hash.hexdigest() 
64 
65 
66 以上加密算法雖然依然非常厲害,但時候存在缺陷,即:通過撞庫可以反解。所以,有必要對加密算法中添加自定義key再來做加密
View Code
import hashlib

# ######## md5 ########
 
hash = hashlib.md5('898oaFs09f')

hash.update('admin')

print hash.hexdigest() 

#還不夠的話,python 還有一個 hmac 模塊,它內部對我們創建 key 和 內容 再進行處理然后再加密

import hmac

h = hmac.new('wueiqi')

h.update('hellowo')

print h.hexdigest() 

json 和 pickle 模塊(用於序列化的兩個模塊)

json--用於字符串 和 python數據類型間進行轉換  (可以用到其他編程語言中去)

pickle--用於python特有的類型 和 python的數據類型間進行轉換

Json模塊提供了四個功能:dumps、dump、loads、load

pickle模塊提供了四個功能:dumps、dump、loads、load

>>> import pickle
>>> data_dic = {'k1':1,'k2':2}
#將數據通過特殊的形式轉換為只有python語言認識的字符串
>>> data_str = pickle.dumps(data_dic)
>>> print(data_str)
b'\x80\x03}q\x00(X\x02\x00\x00\x00k1q\x01K\x01X\x02\x00\x00\x00k2q\x02K\x02u.'

#將只有python語言認識的字符串轉換成數據
>> data_str2 = pickle.loads(data_str)
>>> print(data_str2)
{'k1': 1, 'k2': 2}

#將數據通過特殊的形式轉換為只有python語言認識的字符串,寫入文件
>>> with open('D:/pickdumpsresult.pk','wb') as f:
	pickle.dump(data_dic,f)
	
>>> import json
#將數據通過特殊的形式轉換為全部語言都認識的字符串
>>> j_str = json.dumps(data_dic)
>>> print(j_str)
{"k1": 1, "k2": 2}
#將數據通過特殊的形式轉換為全部語言都認識的字符串,並寫入文件
>>> with open('D:/result.json','w') as f:
	json.dump(data_dic,f)

#將全部語言都認識的字符串轉換成數據
>>> data_str3 = json.loads(j_str)
>>> print(data_str3)
{'k1': 1, 'k2': 2}

執行系統命令 

可以執行shell命令的相關模塊和函數有:
•os.system
•os.spawn*
•os.popen*          --廢棄
•popen2.*           --廢棄
•commands.*      --廢棄,3.x中被移除

下面是在python2.7版本中用commands

>>> import commands
>>> result = commands.getoutput('cmd')
>>> print(result)
'{' 不是內部或外部命令,也不是可運行的程序
或批處理文件。
>>> result1 = commands.getstatus('cmd')
>>> print(result1)
'{' 不是內部或外部命令,也不是可運行的程序
或批處理文件。
>>> result2 = commands.getstatusoutput('cmd')
>>> print(result2)
(1, "'{' \xb2\xbb\xca\xc7\xc4\xda\xb2\xbf\xbb\xf2\xcd\xe2\xb2\xbf\xc3\xfc\xc1\xee\xa3\xac\xd2\xb2\xb2\xbb\xca\xc7\xbf\xc9\xd4\xcb\xd0\xd0\xb5\xc4\xb3\xcc\xd0\xf2\n\xbb\xf2\xc5\xfa\xb4\xa6\xc0\xed\xce\xc4\xbc\xfe\xa1\xa3")

以上提到的模塊執行shell命令的相關的模塊和函數的功能均在 subprocess 模塊中實現,並提供了更豐富的功能

call

執行命令,返回狀態碼

>>> ret = subprocess.call("ls -l", shell=True)
>>> print(ret)
1
#shell = True ,允許 shell 命令是字符串形式,默認是False?

check_call

執行命令,如果執行狀態碼是 0 ,則返回0,否則拋異常

1 check_call
2 
3 >>> ret = subprocess.check_call("ls -l", shell=True)
4 Traceback (most recent call last):
5   File "<pyshell#31>", line 1, in <module>
6     ret = subprocess.check_call("ls -l", shell=True)
7   File "C:\Users\shaopeng\AppData\Local\Programs\Python\Python35\lib\subprocess.py", line 584, in check_call
8     raise CalledProcessError(retcode, cmd)
9 subprocess.CalledProcessError: Command 'ls -l' returned non-zero exit status 1

check_output

執行命令,如果狀態碼是 0 ,則返回執行結果,否則拋異常

 1 >>> subprocess.check_output(["echo", "Hello World!"])
 2 Traceback (most recent call last):
 3   File "<pyshell#33>", line 1, in <module>
 4     subprocess.check_output(["echo", "Hello World!"])
 5   File "C:\Users\shaopeng\AppData\Local\Programs\Python\Python35\lib\subprocess.py", line 629, in check_output
 6     **kwargs).stdout
 7   File "C:\Users\shaopeng\AppData\Local\Programs\Python\Python35\lib\subprocess.py", line 696, in run
 8     with Popen(*popenargs, **kwargs) as process:
 9   File "C:\Users\shaopeng\AppData\Local\Programs\Python\Python35\lib\subprocess.py", line 950, in __init__
10     restore_signals, start_new_session)
11   File "C:\Users\shaopeng\AppData\Local\Programs\Python\Python35\lib\subprocess.py", line 1220, in _execute_child
12     startupinfo)
13 FileNotFoundError: [WinError 2] 系統找不到指定的文件。
14 >>> subprocess.check_output("exit 1", shell=True)
15 Traceback (most recent call last):
16   File "<pyshell#34>", line 1, in <module>
17     subprocess.check_output("exit 1", shell=True)
18   File "C:\Users\shaopeng\AppData\Local\Programs\Python\Python35\lib\subprocess.py", line 629, in check_output
19     **kwargs).stdout
20   File "C:\Users\shaopeng\AppData\Local\Programs\Python\Python35\lib\subprocess.py", line 711, in run
21     output=stdout, stderr=stderr)
22 subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

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()函數,用於設置子進程的一些屬性,如:主窗口的外觀,進程的優先級等等
1 import subprocess
2 ret1 = subprocess.Popen(["mkdir","t1"])
3 ret2 = subprocess.Popen("mkdir t2", shell=True)
#終端輸入的命令分為兩種:1、輸入即可得到輸出,如:ifconfig 2、輸入進行某環境,依賴再輸入,如:python
import subprocess

obj = subprocess.Popen("mkdir t3", shell=True, cwd='/home/dev',)
 1 import subprocess
 2 
 3 obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
 4 obj.stdin.write('print 1 \n ')
 5 obj.stdin.write('print 2 \n ')
 6 obj.stdin.write('print 3 \n ')
 7 obj.stdin.write('print 4 \n ')
 8 obj.stdin.close()
 9 
10 cmd_out = obj.stdout.read()
11 obj.stdout.close()
12 cmd_error = obj.stderr.read()
13 obj.stderr.close()
14 
15 print cmd_out
16 print cmd_error

 

 1 import subprocess
 2 
 3 obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
 4 obj.stdin.write('print 1 \n ')
 5 obj.stdin.write('print 2 \n ')
 6 obj.stdin.write('print 3 \n ')
 7 obj.stdin.write('print 4 \n ')
 8 
 9 out_error_list = obj.communicate()
10 print out_error_list
11 out_error_list = obj.communicate('print "hello"')

12 print out_error_list

shutil

高級的 文件、文件夾、壓縮包 處理模塊

1.shutil.copyfileobj(fsrc, fdst[, length])
將文件內容拷貝到另一個文件中,可以部分內容

2.shutil.copyfile(src, dst)
拷貝文件

3.shutil.copymode(src, dst)
僅拷貝權限。內容、組、用戶均不變

4.shutil.copystat(src, dst)
拷貝狀態的信息,包括:mode bits, atime, mtime, flags

5.shutil.copy(src, dst)
拷貝文件和權限

6.shutil.copy2(src, dst)
拷貝文件和狀態信息

7.shutil.ignore_patterns(*patterns)

shutil.copytree(src, dst, symlinks=False, ignore=None)
遞歸的去拷貝文件

例如:copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))

8.shutil.rmtree(path[, ignore_errors[, onerror]])
遞歸的去刪除文件

9.shutil.move(src, dst)
遞歸的去移動文件

10.shutil.make_archive(base_name, format,...)

創建壓縮包並返回文件路徑,例如:zip、tar

  • base_name: 壓縮包的文件名,也可以是壓縮包的路徑。只是文件名時,則保存至當前目錄,否則保存至指定路徑,
    如:www                        =>保存至當前路徑
    如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/
  • format: 壓縮包種類,“zip”, “tar”, “bztar”,“gztar”
  • root_dir: 要壓縮的文件夾路徑(默認當前目錄)
  • owner: 用戶,默認當前用戶
  • group: 組,默認當前組
  • logger: 用於記錄日志,通常是logging.Logger對象

 

#將 /Users/weishaopeng/Downloads/test 下的文件打包放置當前程序目錄


import shutil

ret = shutil.make_archive("wwwwwwwwww", 'gztar', root_dir='/Users/weishaopeng/Downloads/test')

 
#將 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目錄

import shutil

ret = shutil.make_archive("/Users/weishaopeng/wwwwwwwwww", 'gztar', root_dir='/Users/weishaopeng/Downloads/test')

 shutil 對壓縮包的處理是調用 ZipFile 和 TarFile 兩個模塊來進行的:

import zipfile

# 壓縮
z = zipfile.ZipFile('laxi.zip', 'w')
z.write('a.log')
z.write('data.data')
z.close()

# 解壓
z = zipfile.ZipFile('laxi.zip', 'r')
z.extractall()
z.close()

import tarfile

# 壓縮
tar = tarfile.open('your.tar','w')
tar.add('/Users/weishaoepeng/PycharmProjects/bbs2.zip', arcname='bbs2.zip')
tar.add('/Users/weishaopeng/PycharmProjects/cmdb.zip', arcname='cmdb.zip')
tar.close()

# 解壓
tar = tarfile.open('your.tar','r')
tar.extractall()  # 可設置解壓地址
tar.close()

ConfigParser

用於對特定的配置進行操作,當前模塊的名稱在 python 3.x 版本中變更為 configparser

  1 [section1]
  2 
  3 k1 = v1

  5 k2:v2

  9 [section2]
 10 
 11 k1 = v1 

 83 import ConfigParser

 87 config = ConfigParser.ConfigParser()
 88 
 89 config.read('i.cfg')

 93 # ########## 讀 ##########
 94 
 95 #secs = config.sections()
 96 
 97 #print secs
 98 
 99 #options = config.options('group2')
100 
101 #print options

105 #item_list = config.items('group2')
106 
107 #print item_list

111 #val = config.get('group1','key')
112 
113 #val = config.getint('group1','key')
114 
115  
116 
117 # ########## 改寫 ##########
118 
119 #sec = config.remove_section('group1')
120 
121 #config.write(open('i.cfg', "w"))

125 #sec = config.has_section('wupeiqi')
126 
127 #sec = config.add_section('wupeiqi')
128 
129 #config.write(open('i.cfg', "w"))
135 #config.set('group2','k1',11111)
136 
137 #config.write(open('i.cfg', "w"))

141 #config.remove_option('group2','age')
142 
143 #config.write(open('i.cfg', "w")) 

 logging

用於便捷記錄日志且線程安全的模塊

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 

time

時間相關的操作,時間有三種表示方式:

  • 時間戳               1970年1月1日之后的秒,即:time.time()
  • 格式化的字符串    2014-11-11 11:11,    即:time.strftime('%Y-%m-%d')
  • 結構化時間          元組包含了:年、日、星期等... time.struct_time    即:time.localtime()
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)

random

import random

print random.random()

print random.randint(1,2)

print random.randrange(1,10)

隨機驗證碼實例:

import random

checkcode = ''

for i in range(4):

    current = random.randrange(0,4)

    if current != i:

        temp = chr(random.randint(65,90))

    else:

        temp = random.randint(0,9)

    checkcode += str(temp)

print checkcode

  

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM