zoukankan      html  css  js  c++  java
  • 模块

    sys模块

    argv  执行脚本传入参数。用list存储了命令行的所有参数, 第一个元素是程序本身路径

    path    默认情况下,Python解释器会搜索当前目录、所有已安装的内置模块和第三方模块,搜索路径存放在sys模块的path变量中

    >>> import sys
    >>> sys.path
    ['', '/usr/local/lib/python36.zip', '/usr/local/lib/python3.6', '/usr/local/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/site-packages/readline-6.2.4.1-py3.6-linux-x86_64.egg']

    可以通过sys.path.append添加要搜索的目录,运行结束后失效。

     >>> sys.path.append('/usr/local/lib/my_py_scripts')  

    方法二:设置环境变量

    sys.exit(n)    退出程序,正常退出时exit(0)
    sys.version     获取Python的版本信息
    sys.platform         操作系统的名称
    sys.stdout.write('please:')  
    var=sys.stdin.readline().strip()[-1]

    shutil模块

    copy

    shutil.copyfileobj(open('fsrc','r'),open('fdst','w'))    将一个的内容拷贝到另一个文件里

    shutil.copyfile('srcfile','dstfile') 拷贝文件,返回dstfile

    shutil.copymode(src,dst) 拷贝权限,但是不改变文件内容,所有者,所属组

    shutil.copystat(src,dst) 拷贝权限,最后访问时间,修改时间,不改变文件内容,所有者,所属组

    shutil.copy(src,dst) 拷贝文件到文件或者目录

    shutil.copy2(src,dst) 拷贝文件,也会拷贝元数据,实际是调用shutil.copy()和shutil.copystat()

    shutil.copytree(srcdir,dstdir ) 拷贝目录,dstdir不能存在,否则会报FileExistsError
    shutil.ignore_patterns()

    from shutil import copytree, ignore_patterns
    copytree(srcdir, dstdir, ignore=ignore_patterns('*.pyc', 'tmp*')) # 拷贝除了.pyc tmp*以外的


    shutil.rmtree(dir)     删除目录

    shutil.move(src,dst)     跟mv一样   移动 重命名

    shutil.chown('a.txt',user='root',group='root')     chmod

    >>> shutil.which('ls') 返回命令的可执行文件的路径
    '/usr/bin/ls'
    shutil.disk_usage(path) 检查磁盘空间


    压缩与解压

    压缩:
    shutil.make_archive(base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]]):创建归档文件(如ZIP或TAR),返回其名字。
    base_name 压缩之后的文件名前缀
    format 格式: zip,tar,gztar,bztar,xztar
    root_dir 根目录,默认是当前目录 /tmp
    base_dir 压缩的目录,默认是当前目录 testdir
    owner,group 只用于tar格式的。默认使用当前所有者和组

    >>> shutil.make_archive('test','zip','/tmp','testdir')   压缩/tmp下的testdir目录到test.zip 
    '/tmp/test.zip'

    解压:
    shutil.unpack_archive(filename[,extrac_dir[,format])

    >>> shutil.unpack_archive('test.zip','/opt/test','zip')

    test.zip ---> /opt/test

    # filename 压缩文件的名字
    # extrac_dir 解压后放置的目录,默认当前目录

    # format 解压格式: zip,tar,gztar,bztar,xztar

    hashlib模块

    Python的hashlib 提供了常见的摘要算法,如MD5,SHA,主要提供SHA1,SHA224,SHA256,SHA512,MD5算法。

    md5加密:

    >>> m = hashlib.md5()
    >>> m.update("hello".encode())
    >>> m.update("world".encode())
    >>> m.digest()           # 2进制格式hash
    b'xfc^x03x8d8xa5p2x08TAxe7xfepx10xb0'   
    >>> m.hexdigest()       # 16进制格式hash
    'fc5e038d38a57032085441e7fe7010b0'
    >>> 
    >>> h = hashlib.md5()
    >>> h.update("helloworld".encode())
    >>> h.hexdigest()
    'fc5e038d38a57032085441e7fe7010b0' 
    
    #加密之后不能反解,两个相同字符串加密后的结果是相同的

    sha512:

    >>> s = hashlib.sha512()
    >>> s.update("hello".encode())
    >>> s.hexdigest()
    '9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2dff72519673ca72323c3d99ba5c11d7c7acc6e14b8c5da0c4663475c2e5c3adef46f73bcdec043'

    其他几个加密方法相同

     还有一个hmac模块,它可以对创建 key 和 内容 进行处理然后再加密

    >>> import hmac
    >>> h = hmac.new(b"my_key")
    >>> h.update(b"helloworld")
    >>> h.hexdigest()
    '8e3f6fea98525eeb2faa43260e3a8543'

     subprocess 模块

    run()函数是python3.5中新添加的  在更旧一点的版本里面使用call()函数

    subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, text=None, env=None)

    >>> subprocess.run(['ls','-l'])     #如果命令带有参数,需要以列表形式写
    >>> subprocess.run('ls -l',shell=True)      #或者加上shell=True选项
    total 12
    -rw-r--r-- 1 root root 19932768 Jun 29 16:52 test    # ls -l 命令的结果
    CompletedProcess(args='ls -l', returncode=0)      # run函数的结果

    shell=True:表示执行的是shell命令。 
    subprocess.PIPE:可以用给stdout,stdin,stderr.表示为标准流打开一个管道,常用来捕获子进程的输出和错误. 
    encoding:指出了标准流的编码格式,不指定的话默认是二进制的. 

    >>> subprocess.run('ls -l',shell=True,stdout=subprocess.PIPE)
    CompletedProcess(args='ls -l', returncode=0, stdout=b'total 12
    drwxr-xr-x 2 root root 4096 Nov 14 2017 docker
    drwxr-xr-x 2 root root 4096 Jul 24 17:34 logstashconf
    drwxr-xr-x 4 root root 4096 Nov 14 2017 zou
    ')  
    >>> subprocess.getoutput('ls -l')    #接收字符串格式命令,并返回结果

    Popen()函数    可以处理更复杂一些的交互

    >>> x = subprocess.Popen('ls -l',shell=True,stdout=subprocess.PIPE)
    >>> print(x.stdout.read().decode())
    total 8
    -rw-r--r-- 1 root root 263 Oct 10 11:40 client.py
    -rw-r--r-- 1 root root 399 Oct 10 14:13 server.py
    
    >>> a=subprocess.Popen('find ./ -name test.py -type f ',shell=True,stdout=subprocess.PIPE)
    >>> a
    <subprocess.Popen object at 0x7f7328b33f60>
    >>> a.stdout.read()          # 二进制,需要加.decode() 转化成str
    b'./python/test.py
    ./python/script/test.py
    ' 
    
    cmd_res = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    err = res.stderr.read()
    if err:
        res = err
    else:
        res = res.stdout.read()
    print(res)

     configparser模块

    #写配置文件:
    >>> import configparser
    >>> conf=configparser.ConfigParser()
    >>> conf.add_section('Section1')
    >>> conf.set('Section1','key1','value1')
    >>> conf['Section1']['key2']='value2'
    >>> conf['Section2']={'k3':'v3',
    ...                                 'k4':'v4'}
    >>> conf['Section3']={}
    >>> conf['Section3']['host']='redis.com'
    >>> conf['Section3']['port']='6379'
    >>> with open('test.conf','w') as f:
    ...     conf.write(f)
    
    #  cat test.conf 
    [Section1]
    key1 = value11
    key2 = value2
    
    [Section2]
    k4 = v4
    k3 = v3
    
    [Section3]
    host = redis.com
    port = 6379
    
    #读取配置文件
    >>> import configparser
    >>> conf=configparser.ConfigParser()
    >>> conf.read('test.conf')
    ['test.conf']
    >>> conf.sections()
    ['Section1', 'Section2', 'Section3']
    >>> conf.items('Section3')    # 获取key & value
    [('host', 'redis.com'), ('port', '6379')]

      >>> conf.options('Section3')  # 获取keys
      ['host', 'port']

    #修改
    >>> conf.set('Section3','port','6380')
    >>> conf.write(open('test.conf','w'))
    
    #删除
    >>> conf.remove_section('Section1')
    True
    >>> conf.remove_option('Section3','port')
    True
    >>> conf.write(open('test.conf','w'))
  • 相关阅读:
    数组中的逆序对★★
    把数组排成最小的数★★★
    丑数★★★
    整数中1出现的次数(从1到n整数中1出现的次数)
    连续子数组的最大和
    每两个字符串中插入字符串
    linux R环境安装以及注意事项
    JAVA调用R脚本 windwos路径下
    springboot 配置多数据源
    springboot 在配置文件写参数注入到类中
  • 原文地址:https://www.cnblogs.com/xiaobaozi-95/p/9106235.html
Copyright © 2011-2022 走看看