日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python 必备模块和包_Python_异常和模块

發布時間:2025/3/19 python 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python 必备模块和包_Python_异常和模块 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

異常處理

單個異常處理:

try:

print(num)

except NameError:

print('沒有定義變量')

except FileNotFoundError:

print('找不到文件路徑')

print(1)

多個異常處理:

try:

print(num)

# 11/0

# open('xxx.txt')

except (NameError, FileNotFoundError, ZeroDivisionError): # 多個異常統一處理

print('異常')

print(1)

所有異常處理:

try:

print(num)

except Exception: # 所有異常處理

print('所有異常處理')

print(1)

查看原來異常輸出:

try:

print(num)

except Exception as err:

print(err)

print(1)

沒有異常執行

try:

a = 1

execpt Exception as err:

print(err)

else:

print('沒有異常執行')

finally:

print('不管是否出現異常, 都執行')

print(1)

import time

try:

f = open('test.txt')

try:

while True

content = f.readline()

if len(content) == 0:

break

time.sleep(2)

print(content)

except Exception:

# pass

print('文件產生異常')

finally:

f.close()

print('關閉文件')

except Exception:

print('沒有這個文件')

try與except需要同時存在

當函數嵌套的時候,如果函數出現異常,會返回異常,然后捕獲到異常

拋出自定義異常

raise: 拋出一個自定義異常

raise語句如果不帶參數,就會把當前錯誤原樣拋出。

def main ():

try:

s = input('請輸入-->')

if len(s) < 3:

raise ShortInputException(len(s), 3)

else:

print(s)

except ShortInputException as result:

print('ShortInputException: 輸入的長度是 %d, 長度至少需要是 %d' % (result.length, result.atleast))

else:

print('沒有異常發生.')

class ShortInputException(Exception):

'''自定義異常類'''

def __init__(self, length, atleast):

# super().__init()

self.length = length

self.atleast = atleast

main()

模塊

如何獲取當前模塊的文件名: __file__

引入模塊

import sys導入模塊中的全部功能

from argv import sys, from argv import sys,executable導入模塊中的單獨功能

from sys import *

from sys as s 別名

__name__: 用于表示當前模塊的名字,同時還能反映一個包的結構

導入輸出的是當前模塊名

模塊被直接運行時模塊名為:__main__

if __name__ == '__main__': # 如果模塊是被直接運行的,則代碼塊被運行,如果模塊是被導入的,則代碼塊不被運行。

# code

常用內建模塊

標準庫

說明

builtins

內建函數默認加載

os

操作系統接口 [系統級別的操作(文件和目錄)]

sys

Python自身的運行環境 [對解釋器相關的操作]

functools

常用的工具

json & pickle

編碼和解碼 JSON 對象

logging

記錄日志,調試

multiprocessing

多進程

threading

多線程

copy

拷貝

time

時間

datetime

日期和時間

calendar

日歷

hashlib

加密算法

random

生成隨機數

re

字符串正則匹配

socket

標準的 BSD Sockets API

shutil

文件和目錄管理 [高級的 文件、文件夾、壓縮包 處理模塊(遞歸,文件復制等)]

glob

基于文件通配符搜索

shelve

一個簡單的k,v將內存數據通過文件持久化的模塊,可以持久化任何pickle可支持的python數據格式

hashlib

import hashlib

m = hashlib.md5() # 創建hash對象,md5:(message-Digest Algorithm 5)消息摘要算法,得出一個128位的密文

print m #

m.update('alogy') # 更新哈希對象以字符串參數

print m.hexdigest() # 返回十六進制數字字符串

例子:用于注冊、登錄

import hashlib

import datetime

KEY_VALUE = 'alogy'

now = datetime.datetime.now()

m = hashlib.md5()

str = '%s%s' % (KEY_VALUE,now.strftime("%Y%m%d"))

m.update(str.encode('utf-8'))

value = m.hexdigest()

print(value) # c69c59b58209a94f40e6a7a425f9a977

functools

['WRAPPER_ASSIGNMENTS', 'WRAPPER_UPDATES', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'cmp_to_key', 'partial', 'reduce', 'total_ordering', 'update_wrapper', 'wraps']

partial()

把一個函數的某些參數設置默認值,返回一個新函數,調用這個新函數會更簡單。

import functools

def showarg(*args, **kw):

print(args)

print(kw)

p1 = functools.partial(showarg, 1, 2, 3)

p1()

p1(4,5,6)

p1(a='python', b='alogy')

p2 = functools.partial(showarg, a=3, b='linux')

p2()

p2(1, 2)

p2(a='python', b='alogy')

wraps()

使用裝飾器時,被裝飾后等函數其實已經是另外一個函數(函數名等函數屬性會發生變化)

添加后由于函數名和函數的doc發生了改變,對測試結果有一些影響,例如:

def note(func):

"note function"

def wrapper():

"wrapper function"

print('note something')

return func()

return wrapper

@note

def test():

"test function"

print('I am test')

test()

print(test.__doc__)

運行結果

note something

I am test

wrapper function

所以,Python的functools包中提供了一個叫wraps的裝飾器來消除這樣的副作用。例如:

import functools

def note(func):

"note function"

@functools.wraps(func) # 保存外邊函數名

def wrapper():

"wrapper function"

print('note something')

return func()

return wrapper

@note

def test():

"test function"

print('I am test')

test()

print(test.__doc__)

運行結果

note something

I am test

test function

常用擴展庫

擴展庫

說明

requests

使用的是 urllib3,繼承了urllib2的所有特性

urllib

基于http的高層庫

scrapy

爬蟲

beautifulsoup4

HTML/XML的解析器

celery

分布式任務調度模塊

redis

緩存

Pillow(PIL)

圖像處理

xlsxwriter

僅寫excle功能,支持xlsx

xlwt

僅寫excle功能,支持xls ,2013或更早版office

xlrd

僅讀excle功能

elasticsearch

全文搜索引擎

pymysql

數據庫連接庫

mongoengine/pymongo

mongodbpython接口

matplotlib

畫圖

numpy/scipy

科學計算

django/tornado/flask

web框架

xmltodict

xml 轉 dict

SimpleHTTPServer

簡單地HTTP Server,不使用Web框架

gevent

基于協程的Python網絡庫

fabric

系統管理

pandas

數據處理庫

scikit-learn

機器學習庫

例如:讀寫excel文件

安裝esay_install工具

sudo apt-get install python-setuptools

安裝模塊

sudo easy_install xlrd

sudo easy_install xlwt

所有內置模塊

import sys

sys.modules.keys()

['builtins', 'sys', '_frozen_importlib', '_imp', '_warnings', '_thread', '_weakref', '_frozen_importlib_external', '_io', 'marshal', 'nt', 'winreg', 'zipimport', 'encodings', 'codecs', '_codecs', 'encodings.aliases', 'encodings.utf_8', '_signal', '__main__', 'encodings.latin_1', 'io', 'abc', '_weakrefset', 'site', 'os', 'errno', 'stat', '_stat', 'ntpath', 'genericpath', 'os.path', '_collections_abc', '_sitebuiltins', 'sysconfig', 'idlelib', 'idlelib.run', 'linecache', 'functools', '_functools', 'collections', 'operator', '_operator', 'keyword', 'heapq', '_heapq', 'itertools', 'reprlib', '_collections', 'types', 'collections.abc', 'weakref', 'tokenize', 're', 'enum', 'sre_compile', '_sre', 'sre_parse', 'sre_constants', '_loc

ale', 'copyreg', 'token', 'queue', 'threading', 'time', 'traceback', 'warnings', 'tkinter', '_tkinter', 'tkinter.constants', 'idlelib.autocomplete', 'string', '_string', 'idlelib.autocomplete_w', 'platform', 'subprocess', 'signal', 'msvcrt', '_winapi', 'idlelib.multicall', 'idlelib.config', 'configparser', '_bootlocale', 'encodings.gbk', '_codecs_cn', '_multibytecodec', 'idlelib.hyperparser', 'idlelib.pyparse', 'idlelib.calltips', 'inspect', 'ast', '_ast', 'dis', 'opcode', '_opcode', 'importlib', 'importlib._bootstrap', 'importlib._bootstrap_external', 'importlib.machinery', 'textwrap', 'idlelib.calltip_w', 'idlelib.debugger_r', 'idlelib.debugger', 'bdb', 'fnmatch', 'posixpath', 'idlelib.macosx', 'idlelib.scrolledlist', 'idlelib.windows', 'idlelib.debugobj_r', 'idlelib.rpc', 'pickle', 'struct', '_struct', '_compat_pickle', '_pickle', 'select', 'socket', '_socket', 'selectors', 'math', 'socketserver', 'idlelib.iomenu', 'shlex', 'tempfile', 'shutil', 'zlib', 'bz2', '_compression', '_bz2', 'lzma', '_lzma', 'random', 'hashlib', '_hashlib', '_blake2', '_sha3', 'bisect', '_bisect', '_random', 'locale', 'idlelib.stackviewer', 'idlelib.debugobj', 'idlelib.tree', 'idlelib.zoomheight', 'pydoc', 'importlib.util', 'importlib.abc', 'contextlib', 'pkgutil', 'urllib', 'urllib.parse']

內置全局變量:vars()

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': , '__spec__': None, '__annotations__': {}, '__builtins__': }

第三方模塊:

anaconda: 數十個常用的第三方模塊

內建屬性

python類的內建屬性和方法

['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']

常用專有屬性

說明

觸發方式

__init__

構造初始化函數

創建實例后,賦值時使用,在__new__后

__new__

生成實例所需屬性

創建實例時

__class__

實例所在的類

實例.__class__

__str__

實例字符串表示,可讀性

print(類實例),如沒實現,使用repr結果

__repr__

實例字符串表示,準確性

類實例 回車 或者 print(repr(類實例))

__del__

析構

del刪除實例

__dict__

實例自定義屬性

vars(實例.__dict__)

__doc__

類文檔,子類不繼承

help(類或實例)

__getattribute__

屬性訪問攔截器

訪問實例屬性時

__bases__

類的所有父類構成元素

類名.__bases__

__getattribute__例子:

class Person(object):

def __init__(self, subject1):

self.subject1 = subject1

# 屬性訪問時攔截器,打log

def __getattribute__(self, obj):

if obj == 'subject1':

print('log subject1')

return 'redirect python'

def show(self):

print('this is Person')

p = Person("python")

print(p.subject1)

內建函數

dir(__builtins__)

['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']

range()

range(stop) # 整數列表

range(start, stop[, step]) # 整數列表

strat: 計數從start開始,默認是從0開始。例如:range(5)等價于range(0, 5)

stop: 到stop結束,但不包括stop。例如:range(0, 5), 返回[0, 1, 2, 3, 4]沒有5

step: 每次跳躍的間距,默認為1。例如:range(0, 5)等價于range(0, 5, 1)

map()

map函數會根據提供的函數作為指定序列做映射

map(function, sequence[, sequence, ...]) -> list

function: 一個函數

sequence: 一個或多個序列,取決于function需要幾個參數

返回值是一個list

# 函數需要一個參數

map(lambda x: x*x, [1, 2, 3]) # [1, 4, 9]

# 函數需要兩個參數

map(lambda x, y: x+y, [1, 2, 3], [4, 5, 6]) # [5, 7, 9]

def f1( x, y ):

return (x, y)

l1 = [0, 1, 2, 3, 4, 5, 6]

l2 = ['Sun', 'M', 'T', 'W', 'T', 'F', 'S']

l3 = map(f1, l1, l2)

print(list(l3))

# [(0, 'Sun'), (1, 'M'), (2, 'T'), (3, 'W'), (4, 'T'), (5, 'F'), (6, 'S')]

filter()

filter()會對指定序列執行過濾操作

filter(function or None, sequence) -> list, tuple, or string

function: 接受一個參數,返回布爾值True或False

sequence: 序列可以是str,tuple, list

返回值list, tuple, string

filter(lambda x: x%2, [1, 2, 3, 4])

[1, 3]

filter(None, "a")

'a'

reduce()

reduce會對參數序列中對元素進行累積

reduce(function, sequence[, initial]) -> value

function:該函數有兩個參數

sequence:序列可以是str,tuple,list

initial:固定初始值

function: 該函數有二個參數

sequence: 序列可以是str, tuple, list

initial: 固定初始值

返回value

reduce(lambda x, y: x+y, [1,2,3,4]) # 10

reduce(lambda x, y: x+y, [1,2,3,4], 5) # 15

reduce(lambda x, y: x+y, ['aa', 'bb', 'cc'], 'dd') # 'ddaabbcc'

sorted()

sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

iterable: 迭代器

key: 函數

reverse: 正序,倒序

返回一個新的列表

sorted([1, 4, 2, 6, 3, 5]) # [1, 2, 3, 4, 5, 6]

sorted([1, 4, 2, 6, 3, 5], reverse = 1) # 倒序 # [6, 5, 4, 3, 2, 1]

sorted(['dd', 'aa', 'cc', 'bb']) # ['aa', 'bb', 'cc', 'dd']

lst = [3, -19, -1, 28, 7, 0, -2, -5, 7, 8, 0 -3, 9, 0, 11]

sorted(lst, key=lambda x: (x >= 0, -x if x >= 0 else x)) # [-19, -5, -3, -2, -1, 28, 11, 9, 8, 7, 7, 3, 0, 0] ????

sorted(lst, key=lambda x: (x >= 0, -abs(x))) # [-19, -5, -3, -2, -1, 28, 11, 9, 8, 7, 7, 3, 0, 0] ????

模塊中的__all__的作用

__all__只影響from import *這種導入方式

__all__ = ['test']

def test():

print('test')

包、__init__.py的作用

某個文件夾下具有__init.py的,稱之為包

__init__.py作用:

package的標識

定義package中的__all__,用來模糊導入

模塊的發布和安裝

新建一個setup.py寫入:

from distutils.core import setup

setup(name='alogy', version='1.0', description='a', author='alogy', py_modules=['suba.aa']) # suba.aa 包名.模塊名

發布:

> python setup.py build

> python setup.py sdist

安裝:

> python setup.py install

import搜索路徑

import sys

sys.path # sys.path的先后順序

重新導入模塊

模塊被導入后,import module不能重新導入模塊,需要重新導入

from imp import *

reload('module') # module模塊名

調試

pdb是基于命令行的調試工具

運行時啟動

python -m pdb xxx.py

l: list 查看運行的代碼

n: next 往下行執行

c: continue 繼續執行代碼直到結束

b 7,b 行數: break 添加斷點(通過c執行)

b: 查看所有斷點

clear 斷點序號: 清除指定斷點

s: step 進入當前作用域中

p 變量名: 查看指定變量名的值

a: 查看所有當前作用域的變量名和變量值

q: quit 退出調試

r: return 快速執行到函數最后一行

交互式調試

import pdb

pdb.run('testfun(args)') # 此時會打開pdb調試,注意:先使用s跳轉到testfun函數中,然后可以使用

程序里埋點

當程序執行到pbd.set_trace()位置時停下來調試

import pdb

pdb.set_trace()

package

常用內置模塊:

sys: 系統模塊, 程序與python解釋器的交互, 用于操控python的運行時環境

os: 操作系統模塊, 程序與操作系統的交互, 系統操作IO等行為

time,datetime: 時間模塊

re: 正則

json: json處理

urllib: 網絡處理

random: 隨機

不常用內置模塊:

itertools: 一些特殊的函數可以操作可迭代對象或者排列組合

copy: 拷貝的函數(賦值一般是傳遞對象的引用,修改一個對象,會導致其它對象也受到改變)

string: String模塊包含大量實用常量和類

Naked

Naked: 一個Python命令行應用程序框架. 可用于執行JS代碼

from Naked.toolshed.shell import execute_js, muterun_js

import sys

response = muterun_js('file.js')

if response.exitcode == 0:

print(response.stdout)

else:

sys.stderr.write(str(response.stderr))

shutil

用于復制和歸檔文件和目錄樹的實用函數。

# 清dist目錄

clearDist = (len(sys.argv) == 4 and (sys.argv[3] == '--clear'))

if clearDist:

shutil.rmtree('./dist/')

subprocess

訪問I/O流的子進程

# 編譯vue

buildStat = subprocess.call('node build/build.js ' + webPath + ' ' + verPath, shell=True)

if buildStat != 0:

print('vue 編譯錯誤')

sys.exit(1)

six

import six

def bytes_to_str(s, encoding='utf-8'):

"""Returns a str if a bytes object is given."""

if six.PY3 and isinstance(s, bytes):

return s.decode(encoding)

return s

其它

給程序傳遞參數

import sys

print(sys.argv) # 接收運行時接受的參數

終止程序運行

import sys

sys.exit(1)

總結

以上是生活随笔為你收集整理的python 必备模块和包_Python_异常和模块的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。