Day 17 hash module subprocess module os module sys module configparser module

Application scenarios of the
module : Hash module: Mainly used for file encryption or verification of file integrity.
Subprocess: Mainly used to run operating system commands. Importing subprocess can be understood as importing cmd
os module: Mainly used for environment variables, file directory
sys: Mainly remember sys.path, sys.argv
configparser: read and modify the fixed format configuration file, the suffix of the configuration file is ini or cnf

Three characteristics of hash algorithm
If you pass in a piece of content, you will get a string of hash values. The hash value has three characteristics:
1. If the content passed in is the same as the algorithm used, the hash value must be the same
2. Only the algorithm used It is fixed, the length of the hash value is fixed, and will not grow as the content grows.
3. The hash value is irreversible, and the content cannot be solved by the hash value.
1+2 ==> can be used to verify the file The integrity of
1+3==> can be used for encryption.
Note: To pass the value to the hash factory, you must pass the value of the bytes type.
Insert picture description here
Use the hash algorithm to get the hash value

import hashlib

m = hashlib.md5()  # md5是最简单的一种hash算法,调用md5会得到一个返回值,m就是hash工厂(还有一些其他的算法,比如512算法会让hash值的复杂程度变高)
m.update("你好".encode("utf-8"))     #往hash工厂m里面传值
m.update("nana".encode("utf-8"))
m.update("哈哈".encode("utf-8"))
# 以上传输方式是分批次md5里面传值,传值的结果是:你好nana哈哈

print(m.hexdigest())        #最后得到的hash值:118d65c2111c3c6c357f2041403fccca

Use the hash algorithm to verify the integrity of the file

import hashlib

m = hashlib.md5()
with open(r"D:\pycharm文件\test\practice\c.txt", mode="rb")as f:
    for line in f:
        m.update(line)
    res = m.hexdigest()
    print(res)        # 把hash值和文件一起传给客户端,hash值为:c2ad1c51f02542950e58666460070f2f

Encrypt files with hash algorithm

import hashlib

m = hashlib.md5()
password = "123nana"
m.update(password.encode("utf-8"))
m.update("娜娜".encode("utf-8"))
print(m.hexdigest())

subprocess module

Subprocess is mainly used to run operating system commands. Importing subprocess can be understood as importing cmd of the windows system

import subprocess
import time

obj = subprocess.Popen("tasklist",  # subprocess.Popen开启了一个子进程,sleep后才再pycharm显示结果是因为两个进程共用一个终端
                       shell=True,
                       stdout=subprocess.PIPE,  # 两个进程之间的内存空间是不共享的,主进程想取子进程的结果,使用“管道”可以实现内存共享
                       stderr=subprocess.PIPE
                       )

# time.sleep(3)

stdout_res = obj.stdout.read()  # 该管道调正确的结果
stderr_res = obj.stderr.read()  # 该管道调错误的结果

print(stdout_res.decode("gbk"))  # windows系统解码时gbk格式

os module

The os module is an interface that interacts with the operating system:

os.getcwd() Get the current working directory, that is, the directory path where the current python script works.
os.chdir("dirname") Change the current script working directory; equivalent to cd
os.curdir in the shell. Return the current directory: ('.')
os .pardir Get the string name of the parent directory of the current directory: ('...')
os.makedirs('dirname1/dirname2') can generate a multi-layer recursive directory
os.removedirs('dirname1') If the directory is empty, delete it, and Recursively to the upper-level directory, if it is also empty, delete it, and so on
os.mkdir('dirname') generates a single-level directory; equivalent to mkdir dirname
os.rmdir('dirname') in the shell to delete a single-level empty directory , If the directory is not empty, it cannot be deleted, and an error is reported; equivalent to rmdir dirname
os.listdir('dirname') in the shell to list all files and subdirectories in the specified directory, including hidden files, and print
os.remove( ) Delete a file
os.rename("oldname","newname") Rename file/directory
os.stat('path/filename') Obtain file/directory information
os.sep Output operating system specific path separator, under win Is "\", "/" under Linux
os.linesep outputs the line terminator used by the current platform, "\t\n" under win, "\n" under Linux
os.pathsep outputs the path used to split the file The string win is;, Linux is:
The os.name output string indicates the current platform. win->'nt'; Linux->'posix'
os.system("bash command") Run the shell command and directly display
os.environ Obtain the system environment variable
os.path.abspath(path) Return the normalized absolute path
os .path.split(path) Splits path into a two-tuple of directory and file name and returns
os.path.dirname(path) returns the directory of path. In fact, the first element of
os.path.split(path) os.path.basename(path) returns the last file name of path. If the path ends with / or \, then a null value will be returned. That is, the second element of
os.path.split(path) os.path.exists(path) If path exists, return True; if path does not exist, return False
os.path.isabs(path) If path is an absolute path, Return True
os.path.isfile(path) If path is an existing file, return True. Otherwise it returns False.
os.path.isdir(path) If path is an existing directory, it returns True. Otherwise, it returns False.
os.path.join(path1[, path2[, …]]) returns after combining multiple paths. The parameter before the first absolute path will be ignored.
os.path.getatime(path) returns the path pointed to The last access time of the file or directory
os.path.getmtime(path) returns the last modification time of the file or directory pointed to by
path os.path.getsize(path) returns the size of path

import os

print(os.getcwd())
os.environ["name"] = "nana"         #存储成字典类型,导入os模块直接使用,可以规避循环导入模块的问题
print(os.environ["name"])

os模块path功能的使用
print(os.path.abspath(r"a.txt"))  # 相对路径转成绝对路径  #D:\pycharm文件\test\practice\a.txt
print(os.path.split(r"D:\pycharm文件\test\practice\a.txt"))  # ('D:\\pycharm文件\\test\\practice', 'a.txt')
print(os.path.dirname(r"D:\pycharm文件\test\practice\a.txt"))  # D:\pycharm文件\test\practice
print(os.path.basename(r"D:\pycharm文件\test\practice\a.txt"))  # a.txt
print(os.path.exists(r"D:\pycharm文件\test\practice\a.txt"))   #如果path存在,返回True;如果path不存在,返回False
print(os.path.isabs(r"D:\pycharm文件\test\practice\a.txt"))  # 如果path是绝对路径,返回True
print(os.path.isfile(r"D:\pycharm文件\test\practice\a.txt"))  # 如果path是一个存在的文件,返回True。否则返回False
print(os.path.isdir(r"D:\pycharm文件\test\practice\a.txt"))  # 如果path是一个存在的目录,则返回True。否则返回False
print(os.path.join("D", "a", "b", "c"))    #帮忙拼接路径D\a\b\c
print(os.path.getatime(r"D:\pycharm文件\test\practice\a.txt"))  # 返回path所指向的文件或者目录的最后存取时间
print(os.path.getatime(r"D:\pycharm文件\test\practice\a.txt"))  # 返回path所指向的文件或者目录的最后修改时间
print(os.path.getsize(r"D:\pycharm文件\test\practice\a.txt"))  # 返回path的大小

sys module

1 sys.argv command line parameter list, the first element is the path of the program itself
2 sys.exit(n) exit the program, exit(0) when exiting normally
3 sys.version get the version information of the Python interpreter
4 sys.maxint is the largest The Int value
5 sys.path returns the search path of the module, and the value of the PYTHONPATH environment variable is used during initialization.
6 sys.platform returns the name of the operating system platform

用sys.argv实现拷贝终端的文件内容
import sys

scr_file = sys.argv[1]  # 原文件
dst_file = sys.argv[2]  # 目标文件
with open(r"%s" % scr_file, mode="rb")as f1, \
        open(r"%s" % dst_file, mode="wb")as f2:
    for line in f1:
        f2.write(line)

The configparser module
reads and modifies the fixed format configuration file, the suffix of the configuration file is ini or cnf

读取
import configparser

config = configparser.ConfigParser()
config.read('a.cfg')

# 查看所有的标题
res = config.sections()  # ['section1', 'section2']
print(res)

# 查看标题section1下所有key=value的key
options = config.options('section1')
print(options)  # ['k1', 'k2', 'user', 'age', 'is_admin', 'salary']

# 查看标题section1下所有key=value的(key,value)格式
item_list = config.items('section1')
print(item_list)  # [('k1', 'v1'), ('k2', 'v2'), ('user', 'egon'), ('age', '18'), ('is_admin', 'true'), ('salary', '31')]

# 查看标题section1下user的值=>字符串格式
val = config.get('section1', 'user')
print(val)  # egon

# 查看标题section1下age的值=>整数格式
val1 = config.getint('section1', 'age')
print(val1)  # 18

# 查看标题section1下is_admin的值=>布尔值格式
val2 = config.getboolean('section1', 'is_admin')
print(val2)  # True

# 查看标题section1下salary的值=>浮点型格式
val3 = config.getfloat('section1', 'salary')
print(val3)  # 31.0
改写
import configparser

config = configparser.ConfigParser()
config.read('a.cfg', encoding='utf-8')

# 删除整个标题section2
config.remove_section('section2')

# 删除标题section1下的某个k1和k2
config.remove_option('section1', 'k1')
config.remove_option('section1', 'k2')

# 判断是否存在某个标题
print(config.has_section('section1'))

# 判断标题section1下是否有user
print(config.has_option('section1', ''))

# 添加一个标题
config.add_section('egon')

# 在标题egon下添加name=egon,age=18的配置
config.set('egon', 'name', 'egon')
config.set('egon', 'age', 18)  # 报错,必须是字符串

# 最后将修改的内容写入文件,完成最终的修改
config.write(open('a.cfg', 'w'))

Guess you like

Origin blog.csdn.net/Yosigo_/article/details/112319648