python内置模块

python内置模块
内置模块:
Python中,安装好了Python后,本身就带有的库,就叫做Python的内置的库。
内置模块,也被称为Python的标准库。
python的模块
模块(module):
在python中,xxx.py就是一个模块
模块的使用:
模块的导入问题
常见的系统内置模块的使用:
–math --hashlip --hmac
–random --calendar
–uuid --datetime
–os --sys --time
–base64

round#四舍五入(全局函数)
round(3.333333,4)保留4位小数
math:
该模块主要用于数学计算和相关计算的一个模块
属性:pi#圆周率 e #自然常数
nan#表示不是数字 ceil#向上取整
floor#向下取整 fabs #绝对值
sqrt #开平方 pow#幂平方

random 随机数:
random.random()随机数左闭右开区间
random.randint()【a,b】随机整数
random.uniform()【a,b】随机数
random.choice(容器)将列表元组字典的数据随机选一个元素
random.shuffle(容器)随机打散数据

uuid:128位二进制(换成32,16进制)

os:
[‘DirEntry’, ‘F_OK’, ‘MutableMapping’, ‘O_APPEND’, ‘O_BINARY’
, ‘O_CREAT’, ‘O_EXCL’, ‘O_NOINHERIT’, ‘O_RANDOM’, ‘O_RDONLY’,
‘O_RDWR’, ‘O_SEQUENTIAL’, ‘O_SHORT_LIVED’, ‘O_TEMPORARY’, ‘O_TEXT’,
‘O_TRUNC’, ‘O_WRONLY’, ‘P_DETACH’, ‘P_NOWAIT’, ‘P_NOWAITO’, ‘P_OVERLAY’,
‘P_WAIT’, ‘PathLike’, ‘R_OK’, ‘SEEK_CUR’, ‘SEEK_END’, ‘SEEK_SET’, ‘TMP_MAX’,
‘W_OK’, ‘X_OK’, ‘_AddedDllDirectory’, ‘_Environ’, ‘all’, ‘builtins’,
cached’, ‘doc’, ‘file’, ‘loader’, ‘name’, ‘package’,
spec’, ‘_check_methods’, ‘_execvpe’, ‘_exists’, ‘_exit’, ‘_fspath’,
‘_get_exports_list’, ‘_putenv’, ‘_unsetenv’, ‘_wrap_close’, ‘abc’, ‘abort’,
‘access’, ‘add_dll_directory’, ‘altsep’, ‘chdir’, ‘chmod’, ‘close’, ‘closerange’,
‘cpu_count’, ‘curdir’, ‘defpath’, ‘device_encoding’, ‘devnull’, ‘dup’, ‘dup2’,
‘environ’, ‘error’, ‘execl’, ‘execle’, ‘execlp’, ‘execlpe’, ‘execv’, ‘execve’,
‘execvp’, ‘execvpe’, ‘extsep’, ‘fdopen’, ‘fsdecode’, ‘fsencode’, ‘fspath’, ‘fstat’,
‘fsync’, ‘ftruncate’, ‘get_exec_path’, ‘get_handle_inheritable’, ‘get_inheritable’,
‘get_terminal_size’, ‘getcwd’, ‘getcwdb’, ‘getenv’, ‘getlogin’, ‘getpid’, ‘getppid’,
‘isatty’, ‘kill’, ‘linesep’, ‘link’, ‘listdir’, ‘lseek’, ‘lstat’, ‘makedirs’, ‘mkdir’,
‘name’, ‘open’, ‘pardir’, ‘path’, ‘pathsep’, ‘pipe’, ‘popen’, ‘putenv’, ‘read’, ‘readlink’,
‘remove’, ‘removedirs’, ‘rename’, ‘renames’, ‘replace’, ‘rmdir’, ‘scandir’, ‘sep’,
‘set_handle_inheritable’, ‘set_inheritable’, ‘spawnl’, ‘spawnle’, ‘spawnv’, ‘spawnve’,
‘st’, ‘startfile’, ‘stat’, ‘stat_result’, ‘statvfs_result’, ‘strerror’, ‘supports_bytes_environ’,
‘supports_dir_fd’, ‘supports_effective_ids’, ‘supports_fd’, ‘supports_follow_symlinks’, ‘symlink’,
‘sys’, ‘system’, ‘terminal_size’, ‘times’, ‘times_result’, ‘truncate’, ‘umask’, ‘uname_result’,
‘unlink’, ‘urandom’, ‘utime’, ‘waitpid’, ‘walk’, ‘write’]

curdir返回当前路径,相对路径
getcwdb()绝对路径,返回字节
chdir(path)修改当前工作路径
cpu_cout()获取当前电脑的线程数量
chmod()修改权限(Linux)
defpath()默认查找文件路径
device_encoding 文件编码
os.getpid()获取当前进程的编号
os.getppid()获取当前进程的父进程编号
kill 杀死进程
linesep 获取当前系统的换行符
listdir 获取当前工作空间下的文件及文件夹
mkdir 创建目录,只提供一级目录
mkedirs()创建目录,可以递归创建多级
open()打开或创建文件
remove()删除文件或者目录
removedirs()删除目录
rmdir 删除目录
rename重命名
sep 路径分隔符(两个\)
stat()返回文件状态

from os import path
os.path
[‘all’, ‘builtins’,
cached’, ‘doc’,
file’, ‘loader’, ’
name’, ‘package’, ’
spec’, ‘_abspath_fallback’
, ‘_get_bothseps’, ‘_getfinalpathname’,
‘_getfinalpathname_nonstrict’,
‘_getfullpathname’, ‘_getvolumepathname’,
‘_nt_readlink’, ‘_readlink_deep’, ‘abspath’,
‘altsep’, ‘basename’, ‘commonpath’, ‘commonprefix’,
‘curdir’, ‘defpath’, ‘devnull’, ‘dirname’, ‘exists’, ‘expanduser’,
‘expandvars’, ‘extsep’, ‘genericpath’, ‘getatime’, ‘getctime’,
‘getmtime’, ‘getsize’, ‘isabs’, ‘isdir’, ‘isfile’, ‘islink’, ‘ismount’,
‘join’, ‘lexists’, ‘normcase’, ‘normpath’, ‘os’, ‘pardir’, ‘pathsep’, ’
realpath’, ‘relpath’, ‘samefile’, ‘sameopenfile’, ‘samestat’, ‘sep’, ‘split’,
‘splitdrive’, ‘splitext’, ‘stat’, ‘supports_unicode_filenames’, ‘sys’]

dbspath 获取绝对路径(dbspath=basename+dirname)
altsep 文件分隔符
basename 文件名称
dirname 所属目录
exists()
join() 拼接
split()拆成名称和目录

在函数里用print会输出你print里的东西还会返回NONE,所以用return输出结果

import sys
dir(sys)
[‘breakpointhook’, ‘displayhook’, ‘doc’, ‘excepthook’,
interactivehook’, ‘loader’, ‘name’, ‘package’, ‘spec
, ‘stderr’, ‘stdin’, ‘stdout’, ‘unraisablehook’, ’
_base_executable’, ‘_clear_type_cache’, ‘_current_frames’, ‘_debugmallocstats’,
‘_enablelegacywindowsfsencoding’, ‘_framework’, ‘_getframe’, ‘_git’, ‘_home’,
‘_xoptions’, ‘addaudithook’, ‘api_version’, ‘argv’, ‘audit’, ‘base_exec_prefix’,
‘base_prefix’, ‘breakpointhook’, ‘builtin_module_names’, ‘byteorder’, ‘call_tracing’,
‘callstats’, ‘copyright’, ‘displayhook’, ‘dllhandle’, ‘dont_write_bytecode’, ‘exc_info’
, ‘excepthook’, ‘exec_prefix’, ‘executable’, ‘exit’, ‘flags’, ‘float_info’, ‘float_repr_style’,
‘get_asyncgen_hooks’, ‘get_coroutine_origin_tracking_depth’, ‘getallocatedblocks’, ‘getcheckinterval’,
‘getdefaultencoding’, ‘getfilesystemencodeerrors’, ‘getfilesystemencoding’, ‘getprofile’,
‘getrecursionlimit’, ‘getrefcount’, ‘getsizeof’, ‘getswitchinterval’, ‘gettrace’, ‘getwindowsversion’,
‘hash_info’, ‘hexversion’, ‘implementation’, ‘int_info’, ‘intern’, ‘is_finalizing’, ‘maxsize’, ‘maxunicode’,
‘meta_path’, ‘modules’, ‘path’, ‘path_hooks’, ‘path_importer_cache’, ‘platform’, ‘prefix’, ‘ps1’, ‘ps2’,
‘pycache_prefix’, ‘set_asyncgen_hooks’, ‘set_coroutine_origin_tracking_depth’, ‘setcheckinterval’,
‘setprofile’, ‘setrecursionlimit’, ‘setswitchinterval’, ‘settrace’, ‘stderr’, ‘stdin’, ‘stdout’,
thread_info’, ‘unraisablehook’, ‘version’, ‘version_info’, ‘warnoptions’, ‘winver’]

argv 脚本传参
exit() 退出系统
getdefaultencoding () 获取系统的默认编码
getfilesystemencoding()获取文件编码
getrecursionlimit()获取递归的极限值
setrecursionlimit(num)设置递归极限值
getrefcont()获取对象的引用计数

垃圾回收算法:
引用计数法:缺点:循环引用时无法回收内存

时间和日期模块:
time
[’_STRUCT_TM_ITEMS’, ‘doc’, ‘loader’, ‘name’, ‘package’, ‘spec’,
‘altzone’ ‘asctime’, ‘ctime’, ‘daylight’, ‘get_clock_info’, ‘gmtime’,
‘localtime’, ‘mktime’, ‘monotonic’, ‘monotonic_ns’, ‘perf_counter’,
‘perf_counter_ns’, ‘process_time’, ‘process_time_ns’, ‘sleep’, ‘strftime’,
‘strptime’, ‘struct_time’, ‘thread_time’, ‘thread_time_ns’, ‘time’, ‘time_ns’,
‘timezone’, ‘tzname’]

asctime 当前时间(元组)
ctime 获取当前时间(传秒)

time.gmtime() 获取时间
time.struct_time(tm_year=2020, tm_mon=10, tm_mday=11, tm_hour=3, tm_min=49, tm_sec=48, tm_wday=6, tm_yday=285, tm_isdst=0)
time()获取当前时间戳
sleep(sec)代码休息时间
strftime() 格式化时间
strptime() 讲一个字符串格式时间,转换为日期对象

datetime:

import datetime
dir(datetime)
[‘MAXYEAR’, ‘MINYEAR’, ‘builtins’, ‘cached’,
doc’, ‘file’, ‘loader’, ‘name’, ‘_
package_’, ‘spec’, ‘date’, ‘datetime’,
‘datetime_CAPI’, ‘sys’, ‘time’, ‘timedelta’, ‘timezone’, ‘tzinfo’]

datetime.date(year=2010,month=3,day=5)
datetime.date(2010, 3, 5)
datetime.date(year,month,day)构建一个日期对象

datetime.time(hour[,minuyes][,seconds])构建一个时间对象
datetime.datetime 子模块
导入子模块datetime
方法1 :import datetime
datetime.datetime
方法2:from datetime import datetime

dir(datetime.datetime)
[‘add’, ‘class’, ‘delattr’, ‘dir’, ‘doc’, ‘eq’, ‘format’, ‘ge’, ‘getattribute’, ‘gt’, ‘hash’, ‘init’, ‘init_subclass’, ‘le’, ‘lt’, ‘ne’, ‘new’, ‘radd’, ‘reduce’, ‘reduce_ex’, ‘repr’, ‘rsub’, ‘setattr’, ‘sizeof’, ‘str’, ‘sub’, ‘subclasshook’, ‘astimezone’, ‘combine’, ‘ctime’, ‘date’, ‘day’, ‘dst’, ‘fold’, ‘fromisocalendar’, ‘fromisoformat’, ‘fromordinal’, ‘fromtimestamp’, ‘hour’, ‘isocalendar’, ‘isoformat’, ‘isoweekday’, ‘max’, ‘microsecond’, ‘min’, ‘minute’, ‘month’, ‘now’, ‘replace’, ‘resolution’, ‘second’, ‘strftime’, ‘strptime’, ‘time’, ‘timestamp’, ‘timetuple’, ‘timetz’, ‘today’, ‘toordinal’, ‘tzinfo’, ‘tzname’, ‘utcfromtimestamp’, ‘utcnow’, ‘utcoffset’, ‘utctimetuple’, ‘weekday’, ‘year’]

datetime.astimezone(datetime.now())
datetime.datetime(2020, 10, 11, 14, 47, 25, 762835, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800), ‘中国标 准时间’))
datetime.astimezone(对象) 返回当前是去对应的时间对象
datetime.now() 返回当前时间对象
ctime(时间对象) 一个符合欧美标准的时间字串
time(时间对象)返回时间对象的时间部分
date(时间对象)返回时间对象的日期部分
day 日期

日历模块(calendar)

import calendar
dir(calendar)
[‘Calendar’, ‘EPOCH’, ‘FRIDAY’, ‘February’, ‘HTMLCalendar’,
‘IllegalMonthError’, ‘IllegalWeekdayError’, ‘January’, ‘LocaleHTMLCalendar’,
‘LocaleTextCalendar’, ‘MONDAY’, ‘SATURDAY’, ‘SUNDAY’, ‘THURSDAY’, ‘TUESDAY’,
‘TextCalendar’, ‘WEDNESDAY’, ‘_EPOCH_ORD’, ‘all’, ‘builtins’, ‘cached’,
doc’, ‘file’, ‘loader’, ‘name’, ‘package’, ‘spec’, ‘_colwidth’,
‘_locale’, ‘_localized_day’, ‘_localized_month’, ‘_monthlen’, ‘_nextmonth’, ‘_prevmonth’,
‘_spacing’, ‘c’, ‘calendar’, ‘datetime’, ‘day_abbr’, ‘day_name’, ‘different_locale’,
‘error’, ‘firstweekday’, ‘format’, ‘formatstring’, ‘isleap’, ‘leapdays’, ‘main’, ‘mdays’,
‘month’, ‘month_abbr’, ‘month_name’, ‘monthcalendar’, ‘monthrange’, ‘prcal’, ‘prmonth’,
‘prweek’, ‘repeat’, ‘setfirstweekday’, ‘sys’, ‘timegm’, ‘week’, ‘weekday’, ‘weekheader’]

print(calendar.calendar(2020))打印2020年的日历

hashlib
加密学:
如果通过秘钥是否同一个,可以将加密算法:
对称加密:
DES
可逆加密

非对称加密:(rsa)
加密的秘钥和解密的秘钥并不是使用同一个
rsa生成一对秘钥,公钥和私钥
可逆加密

哈希加密(hash)、散列加密
  不可逆加密,单向,结果唯一
  md5(128位二进制变成32位16进制)

import hashlib
dir(hashlib)
[‘all’, ‘__block_openssl_constructor’, ‘__builtin_constructor_cache’,
builtins’, ‘cached’, ‘doc’, ‘file’, ‘__get_builtin_constructor’
, ‘loader’, ‘name’, ‘package’, ‘spec’, ‘_hashlib’, ‘algorithms_available’
, ‘algorithms_guaranteed’, ‘blake2b’, ‘blake2s’, ‘md5’, ‘new’, ‘pbkdf2_hmac’, ‘scrypt’,
‘sha1’, ‘sha224’, ‘sha256’, ‘sha384’, ‘sha3_224’, ‘sha3_256’, ‘sha3_384’, ‘sha3_512’,
‘sha512’, ‘shake_128’, ‘shake_256’]

encode 将字符转化为字节 encode(“utf-8”)

msg=“123456”

msg.encode(“utf-8”)
b’123456’

type(msg)

c=“545”
type©

c.encode(“utf-8”)
b’545’

type©

a=msg.endode(“utf-8”)
a=msg.encode(“utf-8”)
a
b’123456’

md5.update(“123456”.encode(“utf-8”))
md5

md5.hexdigest()
‘e10adc3949ba59abbe56e057f20f883e’

再次加东西
sha=hashlib.sha256(“123456”.encode(“gbk”))

sha.hexdigest

sha.hexdigest()
‘8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92’

h.update(“123456”.encode(“utf-8”))
Traceback (most recent call last):
File “”, line 1, in
AttributeError: ‘builtin_function_or_method’ object has no attribute ‘update’

sha.update(“12356”.encode(“gbk”))
sha.hexdigest()
‘22e9ff1c1f4f2c030b6a8e53354c1716400f7d511b694e1f2ac6fbd44ee77e40’

hmac:

import hmac
dir(hmac)
[‘HMAC’, ‘builtins’, ‘cached’, ‘doc’, ‘file’, ‘loader’, ‘name’, ‘package’, ‘spec’, ‘_hashlib’, ‘_hashopenssl’, ‘_openssl_md_meths’, ‘_warnings’, ‘compare_digest’, ‘digest’, ‘digest_size’, ‘new’, ‘trans_36’, ‘trans_5C’]

hmac.new(“123456”.encode(“utf-8”),"".encode(“utf-8”),“MD5”)

h=hmac.new(“123456”.encode(“utf-8”),"".encode(“utf-8”),“MD5”)
h.hexdigest()
‘cab1380ea86d8acc9aa62390a58406aa’

你可能感兴趣的:(python内置模块)