zoukankan      html  css  js  c++  java
  • python模块的导入以及模块简介

    一、模块的定义及类型

    1、定义

    模块就是用一堆的代码实现了一些功能的代码的集合,通常一个或者多个函数写在一个.py文件里,而如果有些功能实现起来很复杂,那么就需要创建n个.py文件,这n个.py文件的集合就是模块

    2、类型

    1)自定义模块,自己写的实现自己某些功能需求的.py文件集合

    2)导入的模块

    在你安装python之后,它自己内部的lib文件下就有很多模块可以用,导入后就可以使用,通常路径是C:Python27Lib   (27是版本号,如果是3.5的版本就是C:Python35Lib)

    3)第三方开源模块

    第三方开源模块通常需要自己去下载,这里以linux和windows系统为例子说明

    linux系统

     1 # 下载安装 pycrypto
     2 
     3 wget http://files.cnblogs.com/files/wupeiqi/pycrypto-2.6.1.tar.gz
     4 
     5 tar -xvf pycrypto-2.6.1.tar.gz
     6 
     7 cd pycrypto-2.6.1
     8 
     9 python setup.py build
    10 
    11 python setup.py install
    View Code
    1 #注:在使用源码安装时,需要使用到gcc编译和python开发环境,所以,需要先执行
    2 
    3 yum install gcc
    4 
    5 yum install python-devel
    6 或者
    7 apt-get python-dev 

    安装成功后,模块会自动安装到 sys.path 中的某个目录中,如/usr/lib/python3.5/site-packages

    windows系统

    1.源码安装

    1.设置python的环境变量
    A.控制面板-系统和安全-系统-高级系统设置-环境变量-系统变量-path
    B.将python安装目录添加到里面,我的是C:Python35
    2.到网上下载你需要的模块,并解压,里面有setup.py文件
    3.打开Cmd(命令提示符),切换到解压模块的目录
    4.运行命令:1、setup.py build --> 2、setup.py install
    5.重新打开python IDE, import xxx (模块名称 ),没报错则安装成功
    

    2.用pip3安装

    或者直接切换到 C:Python35Libsite-packages目录下安装
    用pip3 install xxx(要安装的模块名称)然后它就会自己下载了,很简单
    

      

    二、python的模块的导入方式

    #主要包括以下几种导入方式:
    
    1、import moduels(模块名字)   #导入整个模块,这种导入方式比较占用内存
    
    2、import moduels (模块名字)  as  XX             #这里是导入整个模块的同时给它取一个别名,因为有些模块名字比较长,用一个缩写的别名代替在下次用到它时就比较方便
    
    3、from modules(模块名字)  import func(方法)     #从一个模块里导入方法,你要用到模块里的什么方法就从那个模块里导入那个方法,这样占用的内存就比较少
    
    也可以用别名表示 : from modules(模块名字)  import func(方法)as   XX
    
    4、from package.modules   import func(方法)     #从一个包的模块里导入方法 这个方法跟上面那种基本一样,占用的内存也比较少
    
    也可以用别名表示,from modules(模块名字)  import func(方法)as   XX
    

      

    导入模块其实就是告诉Python解释器去解释那个py文件

    导入一个py文件,解释器解释该py文件
    导入一个包,解释器解释该包下的 __init__.py 文件
    

      

     模块导入的路径是以什么为标准的呢,就是以sys.path来查看

    1 >>> import sys
    2 >>> print(sys.path)
    3 ['', 'C:\Users\shaopeng\AppData\Local\Programs\Python\Python35\Lib\idlelib', 

    'C:\Users\shaopeng\AppData\Local\Programs\Python\Python35\python35.zip',
    'C:\Users\shaopeng\AppData\Local\Programs\Python\Python35\DLLs',
    'C:\Users\shaopeng\AppData\Local\Programs\Python\Python35\lib',
    'C:\Users\shaopeng\AppData\Local\Programs\Python\Python35',
    'C:\Users\shaopeng\AppData\Local\Programs\Python\Python35\lib\site-packages']

    如果你要导入的模块不在这些路径下面,你就可以用sys.path.append('你要导入的绝对路径')

    三、python当中用到的模块不少,这里介绍一些常用的模块

    os 模块

     1 os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
     2 os.chdir("dirname")  改变当前脚本工作目录;相当于shell下cd
     3 os.curdir  返回当前目录: ('.')
     4 os.pardir  获取当前目录的父目录字符串名:('..')
     5 os.makedirs('dirname1/dirname2')    可生成多层递归目录
     6 os.removedirs('dirname1')    若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
     7 os.mkdir('dirname')    生成单级目录;相当于shell中mkdir dirname
     8 os.rmdir('dirname')    删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
     9 os.listdir('dirname')    列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
    10 os.remove()  删除一个文件
    11 os.rename("oldname","newname")  重命名文件/目录
    12 os.stat('path/filename')  获取文件/目录信息
    13 os.sep    输出操作系统特定的路径分隔符,win下为"\",Linux下为"/"
    14 os.linesep    输出当前平台使用的行终止符,win下为"	
    ",Linux下为"
    "
    15 os.pathsep    输出用于分割文件路径的字符串
    16 os.name    输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
    17 os.system("bash command")  运行shell命令,直接显示
    18 os.environ  获取系统环境变量
    19 os.path.abspath(path)  返回path规范化的绝对路径
    20 os.path.split(path)  将path分割成目录和文件名二元组返回
    21 os.path.dirname(path)  返回path的目录。其实就是os.path.split(path)的第一个元素
    22 os.path.basename(path)  返回path最后的文件名。如何path以/或结尾,那么就会返回空值。即os.path.split(path)的第二个元素
    23 os.path.exists(path)  如果path存在,返回True;如果path不存在,返回False
    24 os.path.isabs(path)  如果path是绝对路径,返回True
    25 os.path.isfile(path)  如果path是一个存在的文件,返回True。否则返回False
    26 os.path.isdir(path)  如果path是一个存在的目录,则返回True。否则返回False
    27 os.path.join(path1[, path2[, ...]])  将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
    28 os.path.getatime(path)  返回path所指向的文件或者目录的最后存取时间
    29 os.path.getmtime(path)  返回path所指向的文件或者目录的最后修改时间
    View Code

    sys 模块

    用于提供对解释器相关的操作

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

    hashlib 模块

     1 import hashlib
     2 
     3  
     4 
     5 # ######## md5 ########
     6 
     7  
     8 
     9 hash = hashlib.md5()
    10 
    11 hash.update('admin')
    12 
    13 print hash.hexdigest()
    14 
    15  
    16 
    17 # ######## sha1 ########
    18 
    19  
    20 
    21 hash = hashlib.sha1()
    22 
    23 hash.update('admin')
    24 
    25 print hash.hexdigest()
    26 
    27  
    28 
    29 # ######## sha256 ########
    30 
    31  
    32 
    33 hash = hashlib.sha256()
    34 
    35 hash.update('admin')
    36 
    37 print hash.hexdigest()
    38 
    39  
    40 
    41  
    42 
    43 # ######## sha384 ########
    44 
    45  
    46 
    47 hash = hashlib.sha384()
    48 
    49 hash.update('admin')
    50 
    51 print hash.hexdigest()
    52 
    53  
    54 
    55 # ######## sha512 ########
    56 
    57  
    58 
    59 hash = hashlib.sha512()
    60 
    61 hash.update('admin')
    62 
    63 print hash.hexdigest() 
    64 
    65 
    66 以上加密算法虽然依然非常厉害,但时候存在缺陷,即:通过撞库可以反解。所以,有必要对加密算法中添加自定义key再来做加密
    View Code
    import hashlib
    
    # ######## md5 ########
     
    hash = hashlib.md5('898oaFs09f')
    
    hash.update('admin')
    
    print hash.hexdigest() 
    
    #还不够的话,python 还有一个 hmac 模块,它内部对我们创建 key 和 内容 再进行处理然后再加密
    
    import hmac
    
    h = hmac.new('wueiqi')
    
    h.update('hellowo')
    
    print h.hexdigest() 
    

    json 和 pickle 模块(用于序列化的两个模块)

    json--用于字符串 和 python数据类型间进行转换  (可以用到其他编程语言中去)

    pickle--用于python特有的类型 和 python的数据类型间进行转换

    Json模块提供了四个功能:dumps、dump、loads、load

    pickle模块提供了四个功能:dumps、dump、loads、load

    >>> import pickle
    >>> data_dic = {'k1':1,'k2':2}
    #将数据通过特殊的形式转换为只有python语言认识的字符串
    >>> data_str = pickle.dumps(data_dic)
    >>> print(data_str)
    b'x80x03}qx00(Xx02x00x00x00k1qx01Kx01Xx02x00x00x00k2qx02Kx02u.'
    
    #将只有python语言认识的字符串转换成数据
    >> data_str2 = pickle.loads(data_str)
    >>> print(data_str2)
    {'k1': 1, 'k2': 2}
    
    #将数据通过特殊的形式转换为只有python语言认识的字符串,写入文件
    >>> with open('D:/pickdumpsresult.pk','wb') as f:
    	pickle.dump(data_dic,f)
    	
    >>> import json
    #将数据通过特殊的形式转换为全部语言都认识的字符串
    >>> j_str = json.dumps(data_dic)
    >>> print(j_str)
    {"k1": 1, "k2": 2}
    #将数据通过特殊的形式转换为全部语言都认识的字符串,并写入文件
    >>> with open('D:/result.json','w') as f:
    	json.dump(data_dic,f)
    
    #将全部语言都认识的字符串转换成数据
    >>> data_str3 = json.loads(j_str)
    >>> print(data_str3)
    {'k1': 1, 'k2': 2}
    

    执行系统命令 

    可以执行shell命令的相关模块和函数有:
    •os.system
    •os.spawn*
    •os.popen*          --废弃
    •popen2.*           --废弃
    •commands.*      --废弃,3.x中被移除
    

    下面是在python2.7版本中用commands

    >>> import commands
    >>> result = commands.getoutput('cmd')
    >>> print(result)
    '{' 不是内部或外部命令,也不是可运行的程序
    或批处理文件。
    >>> result1 = commands.getstatus('cmd')
    >>> print(result1)
    '{' 不是内部或外部命令,也不是可运行的程序
    或批处理文件。
    >>> result2 = commands.getstatusoutput('cmd')
    >>> print(result2)
    (1, "'{' xb2xbbxcaxc7xc4xdaxb2xbfxbbxf2xcdxe2xb2xbfxc3xfcxc1xeexa3xacxd2xb2xb2xbbxcaxc7xbfxc9xd4xcbxd0xd0xb5xc4xb3xccxd0xf2
    xbbxf2xc5xfaxb4xa6xc0xedxcexc4xbcxfexa1xa3")
    

    以上提到的模块执行shell命令的相关的模块和函数的功能均在 subprocess 模块中实现,并提供了更丰富的功能

    call

    执行命令,返回状态码

    >>> ret = subprocess.call("ls -l", shell=True)
    >>> print(ret)
    1
    #shell = True ,允许 shell 命令是字符串形式,默认是False?

    check_call

    执行命令,如果执行状态码是 0 ,则返回0,否则抛异常

    1 check_call
    2 
    3 >>> ret = subprocess.check_call("ls -l", shell=True)
    4 Traceback (most recent call last):
    5   File "<pyshell#31>", line 1, in <module>
    6     ret = subprocess.check_call("ls -l", shell=True)
    7   File "C:UsersshaopengAppDataLocalProgramsPythonPython35libsubprocess.py", line 584, in check_call
    8     raise CalledProcessError(retcode, cmd)
    9 subprocess.CalledProcessError: Command 'ls -l' returned non-zero exit status 1

    check_output

    执行命令,如果状态码是 0 ,则返回执行结果,否则抛异常

     1 >>> subprocess.check_output(["echo", "Hello World!"])
     2 Traceback (most recent call last):
     3   File "<pyshell#33>", line 1, in <module>
     4     subprocess.check_output(["echo", "Hello World!"])
     5   File "C:UsersshaopengAppDataLocalProgramsPythonPython35libsubprocess.py", line 629, in check_output
     6     **kwargs).stdout
     7   File "C:UsersshaopengAppDataLocalProgramsPythonPython35libsubprocess.py", line 696, in run
     8     with Popen(*popenargs, **kwargs) as process:
     9   File "C:UsersshaopengAppDataLocalProgramsPythonPython35libsubprocess.py", line 950, in __init__
    10     restore_signals, start_new_session)
    11   File "C:UsersshaopengAppDataLocalProgramsPythonPython35libsubprocess.py", line 1220, in _execute_child
    12     startupinfo)
    13 FileNotFoundError: [WinError 2] 系统找不到指定的文件。
    14 >>> subprocess.check_output("exit 1", shell=True)
    15 Traceback (most recent call last):
    16   File "<pyshell#34>", line 1, in <module>
    17     subprocess.check_output("exit 1", shell=True)
    18   File "C:UsersshaopengAppDataLocalProgramsPythonPython35libsubprocess.py", line 629, in check_output
    19     **kwargs).stdout
    20   File "C:UsersshaopengAppDataLocalProgramsPythonPython35libsubprocess.py", line 711, in run
    21     output=stdout, stderr=stderr)
    22 subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

    subprocess.Popen(...)

    用于执行复杂的系统命令

    参数:
    •args:shell命令,可以是字符串或者序列类型(如:list,元组)
    •bufsize:指定缓冲。0 无缓冲,1 行缓冲,其他 缓冲区大小,负值 系统缓冲
    •stdin, stdout, stderr:分别表示程序的标准输入、输出、错误句柄
    •preexec_fn:只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用
    •close_sfs:在windows平台下,如果close_fds被设置为True,则新创建的子进程将不会继承父进程的输入、输出、错误管道。
    所以不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(stdin, stdout, stderr)。
    •shell:同上
    •cwd:用于设置子进程的当前目录
    •env:用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。
    •universal_newlines:不同系统的换行符不同,True -> 同意使用 
    
    •startupinfo与createionflags只在windows下有效
    将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等
    
    1 import subprocess
    2 ret1 = subprocess.Popen(["mkdir","t1"])
    3 ret2 = subprocess.Popen("mkdir t2", shell=True)
    #终端输入的命令分为两种:1、输入即可得到输出,如:ifconfig 2、输入进行某环境,依赖再输入,如:python
    import subprocess
    
    obj = subprocess.Popen("mkdir t3", shell=True, cwd='/home/dev',)
     1 import subprocess
     2 
     3 obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
     4 obj.stdin.write('print 1 
     ')
     5 obj.stdin.write('print 2 
     ')
     6 obj.stdin.write('print 3 
     ')
     7 obj.stdin.write('print 4 
     ')
     8 obj.stdin.close()
     9 
    10 cmd_out = obj.stdout.read()
    11 obj.stdout.close()
    12 cmd_error = obj.stderr.read()
    13 obj.stderr.close()
    14 
    15 print cmd_out
    16 print cmd_error

     

     1 import subprocess
     2 
     3 obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
     4 obj.stdin.write('print 1 
     ')
     5 obj.stdin.write('print 2 
     ')
     6 obj.stdin.write('print 3 
     ')
     7 obj.stdin.write('print 4 
     ')
     8 
     9 out_error_list = obj.communicate()
    10 print out_error_list
    11 out_error_list = obj.communicate('print "hello"')

    12 print out_error_list

    shutil

    高级的 文件、文件夹、压缩包 处理模块

    1.shutil.copyfileobj(fsrc, fdst[, length])
    将文件内容拷贝到另一个文件中,可以部分内容

    2.shutil.copyfile(src, dst)
    拷贝文件

    3.shutil.copymode(src, dst)
    仅拷贝权限。内容、组、用户均不变

    4.shutil.copystat(src, dst)
    拷贝状态的信息,包括:mode bits, atime, mtime, flags

    5.shutil.copy(src, dst)
    拷贝文件和权限

    6.shutil.copy2(src, dst)
    拷贝文件和状态信息

    7.shutil.ignore_patterns(*patterns)

    shutil.copytree(src, dst, symlinks=False, ignore=None)
    递归的去拷贝文件

    例如:copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))

    8.shutil.rmtree(path[, ignore_errors[, onerror]])
    递归的去删除文件

    9.shutil.move(src, dst)
    递归的去移动文件

    10.shutil.make_archive(base_name, format,...)

    创建压缩包并返回文件路径,例如:zip、tar

    • base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
      如:www                        =>保存至当前路径
      如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/
    • format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
    • root_dir: 要压缩的文件夹路径(默认当前目录)
    • owner: 用户,默认当前用户
    • group: 组,默认当前组
    • logger: 用于记录日志,通常是logging.Logger对象

     

    #将 /Users/weishaopeng/Downloads/test 下的文件打包放置当前程序目录
    
    
    import shutil
    
    ret = shutil.make_archive("wwwwwwwwww", 'gztar', root_dir='/Users/weishaopeng/Downloads/test')
    
     
    #将 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目录
    
    import shutil
    
    ret = shutil.make_archive("/Users/weishaopeng/wwwwwwwwww", 'gztar', root_dir='/Users/weishaopeng/Downloads/test')
    

     shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的:

    import zipfile
    
    # 压缩
    z = zipfile.ZipFile('laxi.zip', 'w')
    z.write('a.log')
    z.write('data.data')
    z.close()
    
    # 解压
    z = zipfile.ZipFile('laxi.zip', 'r')
    z.extractall()
    z.close()
    
    import tarfile
    
    # 压缩
    tar = tarfile.open('your.tar','w')
    tar.add('/Users/weishaoepeng/PycharmProjects/bbs2.zip', arcname='bbs2.zip')
    tar.add('/Users/weishaopeng/PycharmProjects/cmdb.zip', arcname='cmdb.zip')
    tar.close()
    
    # 解压
    tar = tarfile.open('your.tar','r')
    tar.extractall()  # 可设置解压地址
    tar.close()

    ConfigParser

    用于对特定的配置进行操作,当前模块的名称在 python 3.x 版本中变更为 configparser

      1 [section1]
      2 
      3 k1 = v1
    
      5 k2:v2
    
      9 [section2]
     10 
     11 k1 = v1 
    
     83 import ConfigParser
    
     87 config = ConfigParser.ConfigParser()
     88 
     89 config.read('i.cfg')
    
     93 # ########## 读 ##########
     94 
     95 #secs = config.sections()
     96 
     97 #print secs
     98 
     99 #options = config.options('group2')
    100 
    101 #print options
    
    105 #item_list = config.items('group2')
    106 
    107 #print item_list
    
    111 #val = config.get('group1','key')
    112 
    113 #val = config.getint('group1','key')
    114 
    115  
    116 
    117 # ########## 改写 ##########
    118 
    119 #sec = config.remove_section('group1')
    120 
    121 #config.write(open('i.cfg', "w"))
    
    125 #sec = config.has_section('wupeiqi')
    126 
    127 #sec = config.add_section('wupeiqi')
    128 
    129 #config.write(open('i.cfg', "w"))
    135 #config.set('group2','k1',11111)
    136 
    137 #config.write(open('i.cfg', "w"))
    
    141 #config.remove_option('group2','age')
    142 
    143 #config.write(open('i.cfg', "w")) 

     logging

    用于便捷记录日志且线程安全的模块

    import logging
    
    logging.basicConfig(filename='log.log',
    
                        format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
    
                        datefmt='%Y-%m-%d %H:%M:%S %p',
    
                        level=10)
    
    logging.debug('debug')
    
    logging.info('info')
    
    logging.warning('warning')
    
    logging.error('error')
    
    logging.critical('critical')
    
    logging.log(10,'log')

    等级分为:

    CRITICAL = 50
    
    FATAL = CRITICAL
    
    ERROR = 40
    
    WARNING = 30
    
    WARN = WARNING
    
    INFO = 20
    
    DEBUG = 10
    
    NOTSET = 0 

    time

    时间相关的操作,时间有三种表示方式:

    • 时间戳               1970年1月1日之后的秒,即:time.time()
    • 格式化的字符串    2014-11-11 11:11,    即:time.strftime('%Y-%m-%d')
    • 结构化时间          元组包含了:年、日、星期等... time.struct_time    即:time.localtime()
    print time.time()
    
    print time.mktime(time.localtime())
    
      
    
    print time.gmtime()    #可加时间戳参数
    
    print time.localtime() #可加时间戳参数
    
    print time.strptime('2014-11-11', '%Y-%m-%d')
    
      
    
    print time.strftime('%Y-%m-%d') #默认当前时间
    
    print time.strftime('%Y-%m-%d',time.localtime()) #默认当前时间
    
    print time.asctime()
    
    print time.asctime(time.localtime())
    
    print time.ctime(time.time())
    
      
    
    import datetime
    
    '''
    
    datetime.date:表示日期的类。常用的属性有year, month, day
    
    datetime.time:表示时间的类。常用的属性有hour, minute, second, microsecond
    
    datetime.datetime:表示日期时间
    
    datetime.timedelta:表示时间间隔,即两个时间点之间的长度
    
    timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
    
    strftime("%Y-%m-%d")
    
    '''
    
    import datetime
    
    print datetime.datetime.now()
    
    print datetime.datetime.now() - datetime.timedelta(days=5)
    

    random

    import random
    
    print random.random()
    
    print random.randint(1,2)
    
    print random.randrange(1,10)
    

    随机验证码实例:

    import random
    
    checkcode = ''
    
    for i in range(4):
    
        current = random.randrange(0,4)
    
        if current != i:
    
            temp = chr(random.randint(65,90))
    
        else:
    
            temp = random.randint(0,9)
    
        checkcode += str(temp)
    
    print checkcode
    

      

     

     

  • 相关阅读:
    Eclipse集成Maven的Web工程demo(独立及Maven集成tomcat)
    Spring Boot的常见配置项解析
    SpringBoot入门demo
    简单句障碍的解决
    阅读理解(2000年统考)
    Java Web项目实战第1篇之环境搭建
    [STM32F10x] 利用定时器测量脉冲宽度
    [STM32F10x] 利用定时器测量频率
    STM32 输入捕获的脉冲宽度及频率计算
    RT-Thread—STM32—在线升级(Ymodem_OTA、HTTP_OTA)
  • 原文地址:https://www.cnblogs.com/wspcoding/p/5634544.html
Copyright © 2011-2022 走看看