python---基础知识回顾(四)(模块sys,os,random,hashlib,re,json,xml,shutil,configparser,logging,datetime,time,集合,堆,双端队列,其他)

前提:dir,__all__,help,__doc__,__file__

dir:可以用来查看模块中的所有特性(函数,类,变量等)

>>> import copy
>>> dir(copy)
[‘Error‘, ‘PyStringMap‘, ‘_EmptyClass‘, ‘__all__‘, ‘__builtins__‘, ‘__cached__‘,
 ‘__doc__‘, ‘__file__‘, ‘__loader__‘, ‘__name__‘, ‘__package__‘, ‘__spec__‘, ‘_c
opy_dispatch‘, ‘_copy_immutable‘, ‘_copy_with_constructor‘, ‘_copy_with_copy_met
hod‘, ‘_deepcopy_atomic‘, ‘_deepcopy_dict‘, ‘_deepcopy_dispatch‘, ‘_deepcopy_lis
t‘, ‘_deepcopy_method‘, ‘_deepcopy_tuple‘, ‘_keep_alive‘, ‘_reconstruct‘, ‘built
ins‘, ‘copy‘, ‘deepcopy‘, ‘dispatch_table‘, ‘error‘, ‘name‘, ‘t‘, ‘weakref‘]
>>> [x for x in dir(copy) if not x.startswith(‘_‘)]
[‘Error‘, ‘PyStringMap‘, ‘builtins‘, ‘copy‘, ‘deepcopy‘, ‘dispatch_table‘, ‘erro
r‘, ‘name‘, ‘t‘, ‘weakref‘]

__all__:(dir中有这个变量)这个变量中包含了一个列表。和我们使用dir加上列表推导式相似。

>>> copy.__all__
[‘Error‘, ‘copy‘, ‘deepcopy‘]

他定义了模块的公有接口,或者说他告诉解释器当我们使用

from copy import *

时,会导入模块的那些函数方法。__all__在编写模块是,可以过滤掉大多不需要的函数方法。若是没有__all__,使用import *会将除了以下划线开头的所有全局名称导入

help:获取帮助,提供日常需要的信息

>>> help(copy)
Help on module copy:

NAME
    copy - Generic (shallow and deep) copying operations.

DESCRIPTION
    Interface summary:
....

>>> help(copy.copy)
Help on function copy in module copy:

copy(x)
    Shallow copy operation on arbitrary Python objects.

    See the module‘s __doc__ string for more info.

引用了__doc__特性,事实上是使用了文档字符串(写在模块开头,或者函数开头的)

__file__:获取文件位置:便于查看文件源代码位置:

>>> copy.__file__
‘C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python35\\lib\\copy
.py‘

一.sys

sys.argv           命令行参数List,第一个元素是程序本身路径

import sys
args = sys.argv[1:] #默认0是程序名
args.reverse()
print(‘,‘.join(args))

D:\MyPython\day24\基础回顾\01装饰器>python test.py ag1 ag2 ag3
ag3,ag2,ag1

sys.exit(n)        退出程序,正常退出时exit(0)

>>> import sys
>>> sys.exit()

sys.version        获取Python解释程序的版本信息  #python --version

>>> sys.version
‘3.5.4 (v3.5.4:3f56838, Aug  8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)]‘

sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值

>>> sys.path
[‘‘, ‘C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python35\\pyth
on35.zip‘, ‘C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python35
\\DLLs‘, ‘C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python35\lib‘, ‘C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python35‘, ‘C
:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python35\\lib\\site-p
ackages‘]

sys.platform       返回操作系统平台名称

>>> sys.platform
‘win32‘

sys.stdin          输入相关  有读取属性r  从屏幕中读取

>>> var = sys.stdin.read()
aasddsa
^Z
>>> var
‘aasddsa\n‘
>>> var = sys.stdin.read(5)
dsad
>>> var
‘dsad\n‘
>>>

sys.stdout         输出相关  有写入属性w  向屏幕中写入

>>> sys.stdout.write(‘dasf‘)
dasf4
>>> sys.stdout.flush()  #刷新当前屏幕  shell中无用

sys.stderror       错误相关  有写入属性w  向屏幕写入(会含有输出错误信息的信息长度)

print(sys.stderr)
print(sys.stderr.write("errfawfa"))

<_io.TextIOWrapper name=‘<stderr>‘ mode=‘w‘ encoding=‘UTF-8‘>
8
errfawfa

二,os

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‘

>>> sys.platform
‘win32‘
>>> os.name
‘nt‘

os.system("bash command")   运行shell命令,直接显示。用于运行外部程序

>>> os.system(‘ls -al‘)
total 50565

os.environ                  获取系统环境变量  在系统中高级环境变量Path设置中的数据
os.path.abspath(path)       返回path规范化的绝对路径
os.path.split(path)         将path分割成目录和文件名二元组返回
os.path.dirname(path)       返回path的目录。其实就是os.path.split(path)的第一个元素,就是返回上级目录

>>> os.path.dirname("c:/sys")
‘c:/‘
>>> os.path.dirname("c:/sys/windows/1.txt")
‘c:/sys/windows‘

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所指向的文件或者目录的最后修改时间  是时间戳

三:random

该模块包括返回随机数的函数。可以用于模拟或者产生随机输出的程序。

>>> random.__all__
[‘Random‘, ‘seed‘, ‘random‘, ‘uniform‘, ‘randint‘, ‘choice‘, ‘sample‘, ‘randrang
e‘, ‘shuffle‘, ‘normalvariate‘, ‘lognormvariate‘, ‘expovariate‘, ‘vonmisesvariat
e‘, ‘gammavariate‘, ‘triangular‘, ‘gauss‘, ‘betavariate‘, ‘paretovariate‘, ‘weib
ullvariate‘, ‘getstate‘, ‘setstate‘, ‘getrandbits‘, ‘SystemRandom‘]

random.__all__

注意:事实上,所产生的数字都是伪随机数,也就是说他们看起来是完全随机的,实际上,他们是以一个可预测的系统作为基础。不过,已经很不错了。若是想实现真正的随机可以使用os中的urandom或者random中的SystemRandom

>>> random.random()        #返回一个在0-之间的随机数
0.5134022843262868
>>> help(random.random)
Help on built-in function random:

random(...) method of random.Random instance
    random() -> x in the interval [0, 1).

>>> random.randint(1,100)      #返回一个在1,100之间的整数
20

>>> random.randrange(1,100)
80

四:hashlib

用于加密相关的操作,代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法

import hashlib

######### md5 ########

h2 = hashlib.md5()

h2.update(bytes(‘123456‘, encoding=‘utf-8‘))
print(h2.hexdigest())    #是字符串十六进制
print(h2.digest())  #是字节byte型   通过.hex()可以转换为上面的字符串十六进制

补充:

digest()

>>> help(hashlib._hashlib.HASH.digest)
Help on method_descriptor:

digest(...)
    Return the digest value as a string of binary data.

返回一个bytes 八位一字节(ASCII),对于(编码的字符,若是ASCII中字符则直接显示,否则按照编码进行转换)b‘\xeaHWo0\xbe\x16i\x97\x16\x99\xc0\x9a\xd0\\\x94‘
对于bytes编码的字符,若是ASCII中字符则直接显示,否则按照编码进行转换
>>> b = bytes("a",encoding="utf-8")
>>> b
b‘a‘
>>> b = bytes("a你",encoding="utf-8")
>>> b
b‘a\xe4\xbd\xa0‘

hexdigest()

>>> help(hashlib._hashlib.HASH.hexdigest)
Help on method_descriptor:

hexdigest(...)
    Return the digest value as a string of hexadecimal digits.

返回一个十六进制字符串str类型‘ea48576f30be1669971699c09ad05c94‘

-------------------------------------------------------------------------------------

digest()转hexdigest()

>>> h2.digest().hex()

-------------------------------------------------------------------------------------

hexdigest()转digest()

需要使用binascii模块

>>> help(binascii)
Help on built-in module binascii:

NAME
    binascii - Conversion between binary data and ASCII用于转换 --- 在二进制和ASCII码之间

binascii中a2b_hex

>>> help(binascii.a2b_hex)
Help on built-in function a2b_hex in module binascii:

a2b_hex(hexstr, /)
    Binary data of hexadecimal representation.将十六进制字符串转化为二进制用bytes类型显示(ASCII)

    hexstr must contain an even number of hex digits (upper or lower case).
    This function is also available as "unhexlify()".其中十六进制必须是偶数

一般我们直接使用十六进制字符串,直接是32位字符串

转换成功:

>>> binascii.a2b_hex(h2.hexdigest())
b‘\xeaHWo0\xbe\x16i\x97\x16\x99\xc0\x9a\xd0\\\x94‘
>>> h2.digest()
b‘\xeaHWo0\xbe\x16i\x97\x16\x99\xc0\x9a\xd0\\\x94‘
>>> h2.hexdigest()
‘ea48576f30be1669971699c09ad05c94‘
>>> binascii.a2b_hex(h2.hexdigest())
b‘\xeaHWo0\xbe\x16i\x97\x16\x99\xc0\x9a\xd0\\\x94‘

-------------------------------------------------------------------------------------

其中md5算法时不能被反解的,但是可以被撞库,获取密码。

更加安全的方法是在加密算法中添加自定义key再来进行加密:

没有key时:

>>> h1 = hashlib.md5(bytes("123456",encoding="utf-8"))
>>> h1.hexdigest()
‘e10adc3949ba59abbe56e057f20f883e‘

上面的数据很容易被撞库获取出来密码。尤其是这些简单的

-------------------------------------------------------------------------------------

使用自定义key时

>>> h2 = hashlib.md5(bytes("asd",encoding="utf-8"))
>>> h2.update(bytes("123456",encoding="utf-8"))
>>> h2.hexdigest()
‘1e55dbf412cb74d5e2c21fb6452408c7‘

相当于使用两次update:

>>> h3 = hashlib.md5()
>>> h3.update(byte("asd",encoding="utf-8"))
>>> h3.update(bytes("123456",encoding="utf-8"))
>>> h3.hexdigest()
‘1e55dbf412cb74d5e2c21fb6452408c7‘

-------------------------------------------------------------------------------------

######## sha1 ########(这些算法的使用和md5相似)

h = hashlib.sha1()
h.update(bytes(‘123456‘, encoding=‘utf-8‘))
print(h.hexdigest())

SHA1, SHA224, SHA256, SHA384, SHA512使用时一样的

-------------------------------------------------------------------------------------

python内置还有一个 hmac 模块,它内部对我们创建 key 和 内容 进行进一步的处理然后再加密

import hmac

h = hmac.new(bytes(‘asd‘,encoding="utf-8"))
h.update(bytes(‘123456‘,encoding="utf-8"))
print(h.hexdigest())#548b23c538c78d7053e3231919f78f36  与上面自定义key得出的密码不一样,说明在内部对key和内容又进行了处理

五:re正则模块

基础了解:正则表达式了解

原文地址:https://www.cnblogs.com/ssyfj/p/8877931.html

时间: 2024-08-29 04:10:50

python---基础知识回顾(四)(模块sys,os,random,hashlib,re,json,xml,shutil,configparser,logging,datetime,time,集合,堆,双端队列,其他)的相关文章

python爬虫主要就是五个模块:爬虫启动入口模块,URL管理器存放已经爬虫的URL和待爬虫URL列表,html下载器,html解析器,html输出器 同时可以掌握到urllib2的使用、bs4(BeautifulSoup)页面解析器、re正则表达式、urlparse、python基础知识回顾(set集合操作)等相关内容。

本次python爬虫百步百科,里面详细分析了爬虫的步骤,对每一步代码都有详细的注释说明,可通过本案例掌握python爬虫的特点: 1.爬虫调度入口(crawler_main.py) # coding:utf-8from com.wenhy.crawler_baidu_baike import url_manager, html_downloader, html_parser, html_outputer print "爬虫百度百科调度入口" # 创建爬虫类class SpiderMai

Python time、datetime、os、random、sys、hashlib、json、shutil、logging、paramiko模块的使用

1.time & datetime模块 #_*_coding:utf-8_*_ import time import datetime print(time.clock()) #返回处理器时间,3.3开始已废弃 print(time.process_time()) #返回处理器时间,3.3开始已废弃 print(time.time()) #返回当前系统时间戳 print(time.ctime()) #输出Tue Jan 26 18:23:48 2016 ,当前系统时间 print(time.ct

Python基础知识10(模块与包库的安装使用)

(1)使用标准库#标准库: Python安装包里面提供的功能模块和包主要包括内置类型和函数 #比如len.int.open等 #直接使用,无需import 功能模块 #包含程序设计所需的常用的功能 #需要用import导入他们就可以使用 import timeprint(time.strftime("%Y_%m_%d %H:%M:%S")) #打印结果如下2018_06_17 11:06:16 ----------------------------------------------

python基础知识回顾

参考教程 (一)数据类型 整数/浮点数 字符串用单引号或双引号括起来的文本转义字符:在被转义的字符前加下划线(例如‘\\’表示‘\’) 布尔值 True False(区分大小写)布尔值可进行and.or.not运算 空值 None 变量 python是动态语言 常量 习惯用大写变量名表示 (二)list.tuple.dict.set list用 [] 表示,支持len().append().insert().pop() tuple用()表示,一旦初始化不能修改 dict字典,用 {} 表示 d

python基础知识回顾之字符串

字符串是python中使用频率很高的一种数据类型,内置方法也是超级多,对于常用的方法,还是要注意掌握的. #author: Administrator #date: 2018/10/20 # python3 '''字符串的内置方法''' '''字符串的这些方法很重要''' st='hello kitty {name} is {age}' #创建一个字符串. print(st.count('{')) #计数 print(st.capitalize()) #把字符串的第一个字母大写,整个字符串的首字

Python基础知识(四)

>>列表类型内建函数 ->list.append(obj)  向列表中添加一个对象obj ->list.count(obj) 返回一个对象obj 在列表中出现的次数 ->list.extend(seq) 把序列seq 的内容添加到列表中 ->list.index(obj, i=0,j=len(list)) 返回list[k] == obj 的k 值,并且k 的范围在 i<=k<j;否则引发ValueError 异常. ->list.insert(ind

python基础知识第四篇(元组)

元组 list列表 li[11,22,33,44]列表和元组的区别:元素不可被修改,不可被增加或者删除(一级元素),列表则相反 tuple元组 tu=(111,222,333,444) 支持索引取值 支持切片取值 可以for循环 字符串,列表,元组可以相互转换 元组的一级元素不可修改或者删除或者增加,但是元组里面的列表的值可以被修改等等 v=tu.cound() 找到指定元素在元组中出现的次数 tu.index() 获取某个元素的索引位置 原文地址:https://www.cnblogs.com

Python基础知识(四)—容器类型

容器类型 一.通用操作 1.数学运算符 +:用于拼接两个容器 +=:用原容器与右侧容器拼接,并重新绑定变量 *:重复生成容器元素 *=:用原容器生成重复元素, 并重新绑定变量 < <= > >= == !=:依次比较两个容器中元素,一但不同则返回比较结果. 2.成员运算符 语法: 数据 in 序列 数据 not in 序列 作用:如果在指定的序列中找到值,返回bool类型. # 成员运算 str01 = "我叫苏大强" print("大苏"

JS基础知识回顾:引用类型(四)

每个函数都是Function类型的实例,而且都与其他引用类型一样具有属性和方法. 由于函数是对象,因此函数名实际上也是一个指向函数对象的指针,不会与某个函数绑定. 函数的声明有以下三种形式: function sum(num1,num2){return num1+num2;}//利用函数声明语法定义 var sum=function(num1,num2){return num1+num2;}//利用函数表达式定义 var sum=new Function("num1","nu