zoukankan      html  css  js  c++  java
  • python-----模塊(os、sys、hmac、hashlib、logging、configparser)


    # os模块
    # 提供对操作系统进行调用的接口
    import os

    # print(os.getcwd()) # 获取当前工作目录
    # print(os.chdir(r'D:PycharmProjects')) # change dir改变当前工作目录
    #
    # print(os.curdir) # .
    # print(os.pardir) # ..
    #
    #
    # os.getcwd() # 获取当前工作目录,即当前python脚本工作的目录路径
    # os.chdir("dirname") # 改变当前脚本工作目录;相当于shellcd
    # os.curdir # 返回当前目录: ('.')
    # os.pardir # 获取当前目录的父目录字符串名:('..')
    # os.makedirs('dirname1/dirname2') # 可生成多层递归目录
    # os.removedirs('dirname1') # 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
    # os.mkdir('dirname') # 生成单级目录;相当于shellmkdir dirname
    # os.rmdir('dirname') # 删除单级空目录,若目录不为空则无法删除,报错;相当于shellrmdir dirname
    # os.listdir('dirname') # 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
    # os.remove() # 删除一个文件
    # os.rename("oldname", "newname") # 重命名文件 / 目录
    # os.stat('path/filename') # 获取文件 / 目录信息
    # os.sep # 输出操作系统特定的路径分隔符,win下为 "\", Linux下为 "/"
    # os.linesep # 输出当前平台使用的行终止符,win下为" ", Linux下为 " "
    # os.pathsep # 输出用于分割文件路径的字符串
    # os.name # 输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
    # os.system("bash command") # 运行shell命令,直接显示
    # os.environ # 获取系统环境变量
    # os.path.abspath(path) # 返回path规范化的绝对路径
    # os.path.split(path) # path分割成目录和文件名二元组返回
    # os.path.dirname(path) # 返回path的目录。其实就是os.path.split(path)的第一个元素
    # 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所指向的文件或者目录的最后修改时间



    # *****************************************************************
    # sys模塊

    # sys.argv 命令行参数List,第一个元素是程序本身路径
    # sys.exit(n) 退出程序,正常退出时exit(0)
    # sys.version 获取Python解释程序的版本信息
    # sys.maxint 最大的Int
    # sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
    # sys.platform 返回操作系统平台名称
    # sys.stdout.write('please:')
    # val = sys.stdin.readline()[:-1]

    # ************************************************************
    #hashlib模塊: 用于加密相关的操作,3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 MD5 算法

    # import hashlib
    #
    # m = hashlib.md5()
    # m.update(b"Hello")
    # m.update(b"It's me")
    # print(m.digest())
    # m.update(b"It's been a long time since last time we ...")
    #
    # print(m.digest()) # 2进制格式hash
    # print(len(m.hexdigest())) # 16进制格式hash
    # '''
    # def digest(self, *args, **kwargs): # real signature unknown
    # """ Return the digest value as a string of binary data. """
    # pass
    #
    # def hexdigest(self, *args, **kwargs): # real signature unknown
    # """ Return the digest value as a string of hexadecimal digits. """
    # pass
    #
    # '''
    # import hashlib
    #
    # # ######## md5 ########
    #
    # hash = hashlib.md5()
    # hash.update('admin'.encode('utf8'))
    # print(hash.hexdigest())
    #
    # # ######## sha1 ########
    #
    # hash = hashlib.sha1()
    # hash.update('admin'.encode('utf8'))
    # print(hash.hexdigest())
    #
    # # ######## sha256 ########
    #
    # hash = hashlib.sha256()
    # hash.update('admin'.encode('utf8'))
    # print(hash.hexdigest())
    #
    # # ######## sha384 ########
    #
    # hash = hashlib.sha384()
    # hash.update('admin'.encode('utf8'))
    # print(hash.hexdigest())
    #
    # # ######## sha512 ########
    #
    # hash = hashlib.sha512()
    # hash.update('admin'.encode('utf8'))
    # print(hash.hexdigest())


    # **********************************************************
    # hmac 模块:它内部对我们创建 key 和 内容 再进行处理然后再加密

    # import hmac
    # h = hmac.new(b'天王盖地虎', b'宝塔镇河妖')
    # print h.hexdigest()


    # ***********************************************************

    # logging模塊:很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误、警告等信息输出,
    # pythonlogging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,logging的日志可以分为 debug(), info(), warning(), error() and critical() 5个级别,


    # import logging
    #
    # logging.basicConfig(
    # level = logging.DEBUG,
    # format = '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
    # datefmt = '%a, %d %b %Y %H:%M:%S',
    # filename ='test',
    # filemode = 'a+')
    #
    # logging.debug('debug message')
    # logging.info('info message')
    # logging.warning("user [alex] attempted wrong password more than 3 times")
    # logging.critical("server is down")
    # logging.error('error message')
    #
    # # 输出
    # # WARNING: root:user[alex] attempted wrong more than 3 times
    # # CRITICAL: root:server is down
    # # ERROR:root:error message
    #
    #
    # logger = logging.getLogger()
    # # 創建一個handler,用於寫入日誌文件
    # fh = logging.FileHandler('test.log')
    #
    # # 在創建一個handler,用於輸出到控制臺
    # ch = logging.StreamHandler()
    #
    # formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    #
    # fh.setFormatter(formatter)
    # ch.setFormatter(formatter)
    #
    # logger.addHandler(fh)
    # logger.addHandler(ch)
    #
    # logging.debug('debug message')
    # logging.info('info message')
    # logging.warning("user [alex] attempted wrong password more than 3 times")
    # logging.critical("server is down")
    # logging.error('error message')


    # *******************************************************

    # configparser模塊:配置模塊


    # import configparser
    #
    # config = configparser.ConfigParser()
    # config["DEFAULT"] = {'ServerAliveInterval': '45',
    # 'Compression': 'yes',
    # 'CompressionLevel': '9'}
    #
    # config['bitbucket.org'] = {}
    # config['bitbucket.org']['User'] = 'hg'
    #
    # config['topsecret.server.com'] = {}
    # topsecret = config['topsecret.server.com']
    # topsecret['Host Port'] = '50022' # mutates the parser
    # topsecret['ForwardX11'] = 'no' # same here
    # config['DEFAULT']['ForwardX11'] = 'yes'
    #
    # with open('example.ini', 'w') as configfile:
    # config.write(configfile)

    # ***************************************************
    # config
    # >>> import configparser
    # >>> config = configparser.ConfigParser()
    # >>> config.sections()
    # []
    # >>> config.read('example.ini')
    # ['example.ini']
    # >>> config.sections()
    # ['bitbucket.org', 'topsecret.server.com']
    # >>> 'bitbucket.org' in config
    # True
    # >>> 'bytebong.com' in config
    # False
    # >>> config['bitbucket.org']['User']
    # 'hg'
    # >>> config['DEFAULT']['Compression']
    # 'yes'
    # >>> topsecret = config['topsecret.server.com']
    # >>> topsecret['ForwardX11']
    # 'no'
    # >>> topsecret['Port']
    # '50022'
    # >>> for key in config['bitbucket.org']: print(key)
    # ...
    # user
    # compressionlevel
    # serveraliveinterval
    # compression
    # forwardx11
    # >>> config['bitbucket.org']['ForwardX11']
    # 'yes'

    #*******************************************
    # configparser增删改查语法:删remove set覆盖 查has


    [section1]
    k1 = v1
    k2: v2

    [section2]
    k1 = v1

    import ConfigParser

    config = ConfigParser.ConfigParser()
    config.read('i.cfg')

    # ########## ##########
    # secs = config.sections()
    # print secs
    # options = config.options('group2')
    # print options

    # item_list = config.items('group2')
    # print item_list

    # val = config.get('group1','key')
    # val = config.getint('group1','key')

    # ########## 改写 ##########
    # sec = config.remove_section('group1')
    # config.write(open('i.cfg', "w"))

    # sec = config.has_section('wupeiqi')
    # sec = config.add_section('wupeiqi')
    # config.write(open('i.cfg', "w"))


    # config.set('group2','k1',11111)
    # config.write(open('i.cfg', "w"))

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

    # *******************************************************
    无论你选择做什么,追求完美的程度决定你成就的高度。
  • 相关阅读:
    Javaweb学习12.4
    Javaweb学习11.23
    Javaweb学习11.29
    Javaweb学习12.3
    Javaweb学习12.1
    Javaweb学习11.27
    2020年8月25日Java学习日记
    2020年8月18日Java学习日记
    2020年8月22日Java学习日记
    2020年8月21日Java学习日记
  • 原文地址:https://www.cnblogs.com/chiyhua/p/12605297.html
Copyright © 2011-2022 走看看