Python--day5--常用模块

介绍:

本文主要是学习python常用模块的记录,后面记录的不是很详细,以后再补。

2016年12月27日

目录:

  1. 模块介绍
  2. json & pickle
  3. time  &   datetime模块 &月历
  4. random模块
  5. OS
  6. SYS
  7. shutil
  8. shelves
  9. xml
  10. yaml
  11. ConfigParser
  12. hashlib
  13. subprocess
  14. logging


模块


就是用一堆代码实现某个功能的代码集合。

模块分三种:

  • 自定义模块
  • 内置标准模块(标准库)
  • 开源模块

开源模块网站   :  pypi.python.org

调用模块

调用

from backend.logic   import handle  ##这样导入目录必须是包的状态,也就是包下面 有一个 __init__.py

handle.home()

sql.py

import sys
import  os.path
base_dir=os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) ##获得目录
sys.path.append(base_dir)  ##修改库的目录
from  config    import settings
def  db_auth(configs):
    if  configs.DATABASE["user"]  ==  ‘root‘  and  configs.DATABASE["password"] == "123":
        print("OK")
        return True
    else:
        print("error")
def s(table,column):
    if  db_auth(settings):
        if table == ‘user‘:
            user_info = {
                "001":[‘hequan‘,24,‘engineer‘],
                "002":[‘he123‘, 44, ‘beijing‘],
                "003":[‘he456‘, 55, ‘hebei‘],
        }
            return  user_info
    else:
        print("cuowu.......")

handle.py

import sys
import  os.path
base_dir=os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(base_dir)
from back.db.sql  import s
def  home():
    print("welcome to home page")
    q_data = s("user",‘xxx‘)
    print("query res: {}".format(q_data))
def movie():
    print("welcome to movie page")
def  tv():
    print("welcome to tv  page")

settings.py

DATABASE ={
    "engine":"mysql",
    "host":"localhost",
    "port":3306,
    "user":"root",
    "password":"123",
}

user_main.py

from back.logic  import handle
handle.home()
结果
welcome to home page
OK
query res: {‘003‘: [‘he456‘, 55, ‘hebei‘], ‘001‘: [‘hequan‘, 24, ‘engineer‘], ‘002‘: [‘he123‘, 44, ‘beijing‘]}


json&pickle  序列化

  • json     用于字符串和python数据类型间进行转化                           r   w
  • pickle  用于python特有的类型和python的数据类型间进行转换      rb  wb   支持更复杂的调用函数

都提供了4个功能:  dumps\dump\loads\load

例子

pickle写入
import  pickle
f =open("user.txt","wb")    ##json  只是w
info={
    "user":"123",
    "hequan":‘123‘
}
f.write(pickle.dumps(info))
f.close()

读取
import pickle
f= open("user.txt",‘rb‘)  
data =pickle.loads(f.read())
print(data)
dumps 与 dump的 区别
pickle.dump(info,f)    ##写入
data =pickle.load(f)   ##读取


time

import   time

时间元祖

序号 字段
0 4位数年    tm_year 2008
1 月        tm_mon 1 到 12
2 日         tm_day 1到31
3 小时      tm_hour 0到23
4 分钟    tm_min 0到59
5 秒     tm_sec 0到61 (60或61 是闰秒)
6 一周的第几日     tm_wday 0到6 (0是周一)
7 一年的第几日      tm_yday 1到366 (儒略历)
8 夏令时     tm_isdst -1, 0, 1, -1是决定是否为夏令时的旗帜

获取当前时间

import  time
localtime = time.localtime(time.time())
print(localtime)
time.struct_time(tm_year=2016, tm_mon=12, tm_mday=27, tm_hour=16, tm_min=46, tm_sec=44, tm_wday=1, tm_yday=362, tm_isdst=0)

获取格式化时间
localtime = time.asctime(time.localtime(time.time()))
print(localtime)
Tue Dec 27 16:47:56 2016

格式化日期
print(time.strftime("%Y-%m-%d  %H:%M:%S",time.localtime()))
2016-12-27  16:49:16

月历
import calendar
cat = calendar.month(2017,1)
print(cat)
    January 2017
Mo Tu We Th Fr Sa Su
                   1
 2  3  4  5  6  7  8
 9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31

datetime

import datetime
date = datetime.datetime.now()
print(date)
2016-12-27 16:54:42.472913


random模块

随机数

random.randint(a, b),                           用于生成一个指定范围内的整数。其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b

random.randrange([start], stop[, step])  从指定范围内,按指定基数递增的集合中 获取一个随机数。如:random.randrange(10, 100, 2),结果相当于从[10, 12, 14, 16, ... 96, 98]序列中获取一个随机数。



os模块

os.popen("dir").read()     执行命令,暂时保存到一个地方

os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径

os.chdir("dirname")  改变当前脚本工作目录;相当于shell下cd

os.curdir  返回当前目录: (‘.‘)

os.pardir  获取当前目录的父目录字符串名:(‘..‘)

os.makedirs(‘dirname1/dirname2‘)    可生成多层递归目录

os.removedirs(‘dirname1‘)    若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推

os.mkdir(‘dirname‘)    生成单级目录;相当于shell中mkdir dirname

os.rmdir(‘dirname‘)    删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname

os.listdir(‘dirname‘)    列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印

os.remove()  删除一个文件

os.rename("oldname","newname")  重命名文件/目录

os.stat(‘path/filename‘)  获取文件/目录信息

os.sep    输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"

os.linesep    输出当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"

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]



shutil 文件  文件夹 处理模块

shutil.copyfileobj(fsrc, fdst[, length])

将文件内容拷贝到另一个文件中,可以部分内容

def copyfileobj(fsrc, fdst, length=16*1024):

"""copy data from file-like object fsrc to file-like object fdst"""

while 1:

buf = fsrc.read(length)

if not buf:

break

fdst.write(buf)

shutil.copyfile(src, dst)

拷贝文件

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

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

shutil.copy(src, dst)

拷贝文件和权限

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

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

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

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

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

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对象

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



shelve

是一个简单的k,v 将内存数据通过文件持久化的模块,支持pickle

import shelve

d = shelve.open(‘shelve_test‘) #打开一个文件

class Test(object):

def __init__(self,n):

self.n = n

t = Test(123)

t2 = Test(123334)

name = ["alex","rain","test"]

d["test"] = name #持久化列表

d["t1"] = t      #持久化类

d["t2"] = t2

d.close()



xml模块

实现不同语言或程序直接进行数据交换   <>



yaml

http://pyyaml.org/wiki/PyYAMLDocumentation



configparser模块

用于生成和修改常见配置文档。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
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)
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes
[bitbucket.org]
user = hg
[topsecret.server.com]
host port = 50022
forwardx11 = no


hashlib模块

加密操作



subprocess模块



logging

提供了标准的日志接口。

分5个级别

debug() info()  warning()  error()  critical()

import logging
 
logging.warning("user [alex] attempted wrong password more than 3 times")
logging.critical("server is down")
 
#输出
WARNING:root:user [alex] attempted wrong password more than 3 times
CRITICAL:root:server is down

import logging
 
logging.basicConfig(filename=‘example.log‘,level=logging.INFO)
logging.debug(‘This message should go to the log file‘)
logging.info(‘So should this‘)
logging.warning(‘And this, too‘)
时间: 2024-08-07 04:31:10

Python--day5--常用模块的相关文章

python学习笔记day5——常用模块学习

一.主要内容 模块介绍 time &datetime模块 random os sys shutil json & picle shelve xml处理 yaml处理 configparser hashlib subprocess logging模块 re正则表达式 二.具体内容 1.模块 a.定义:本质就是.py结尾的python文件,逻辑上组织python代码,实现某种功能.例:文件名test.py-->模块名test. b.导入方法:imort moduname from mdn

Python之路-python(常用模块学习)

模块介绍 time &datetime模块 random os sys shutil shelve xml处理 yaml处理 configparser hashlib re正则表达式 1.模块: 定义:其实模块简单说就是一堆代码实现某个功能,它们是已经写好的.py文件.只需要用import应用即可. 分类: 1.自定义模块 2.内置标准模块(又称标准库) 3.开源模块    1.自定义模块,就是自己写的.py文件为了实现某个功能.    2.内置模块,就是python自身已经写好的某个功能,例如

Day5 - 常用模块学习

本节大纲: 模块介绍(模块导入方法) time &datetime模块 random os sys shutil json & picle shelve xml处理 yaml处理 configparser hashlib subprocess logging模块 re正则表达式 模块,用一堆代码实现了某个功能的代码集合. 类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合.而对于一个复杂的功能来,可能需要多个函数才能完成(函数又

python基础--常用模块与面向对象基础

1常用模块 1.1 xml xml是实现不同语言或程序之间进行数据交换的协议 xml的格式如下: <?xml version="1.0"?> <data> <country name="Liechtenstein"> <rank updated="yes">2</rank> <year>2008</year> <gdppc>141100</gdp

Python(六)-常用模块

目录: 1.模块介绍 2.time & datetime模块 3.rendom 4.os 5.sys 6.shutil 7.json & picle 8.shelve 9.xml处理 10.yaml处理 11.chonfigparser 12.hashlib 13.subprocess 14.logging模块 15.re正则表达式 第一章:模块介绍 模块,用一坨代码实现了某个功能的代码集合. 类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用

python编程常用模块记录

time(时间相关模块) logging(日志模块) [time 模块] 与时间有关还有datetime.calendar等 time模块常用于获取当前系统日期时间,该值可用于日志文件命名或者任何sleep函数让进程挂起. 常用用法: 一.现在需要知道当前时间,转换为字符串: #! /usr/bin/env python #coding=utf-8 import time print time.strftime('%Y-%m-%d %A %X %Z',time.localtime(time.ti

python中常用模块详解二

log模块的讲解 1 Python 使用logging模块记录日志涉及四个主要类,使用官方文档中的概括最为合适: 2 3 logger提供了应用程序可以直接使用的接口API: 4 handler将(logger创建的)日志记录发送到合适的目的输出: 5 formatter决定日志记录的最终输出格式 6 filter提供了细度设备来决定输出哪条日志记录: 7 8 logger 9 每个程序在输出信息之前都要获得一个Logger.Logger通常对应了程序的模块名, 10 比如聊天工具的图形界面模块

Python 20 常用模块01

常用模块01 1. 模块的简单认识 引入模块的方式: import 模块 from xxx import 模块 . 比如, random, os, sys, collections等等. 那我们?前?到的所有模块都是python内 置的模块 2. collections模块 ollections模块主要封装了?些关于集合类的相关操作. 比如, 我们学过的Iterable, Iterator等等. 除了这些以外, collections还提供了?些除了基本数据类型以外的数据集合类 型. Count

Python 22 常用模块03

常用模块03 re 1. 正则表达式 正则表达式是对字符串操作的各种逻辑公式. 我们一般使用正则表达式对字符串进行匹配和过滤 字符组 字符组很简单用[]括起来. 在[]中出现的内容会被匹配. 例如:[abc] 匹配a或b或c 如果字符组中的内容过多还可以使用- , 例如: [a-z] 匹配a到z之间的所有字母 [0-9] 匹配所有阿拉伯数字 简单元字符 基本的元字符: . 匹配除换行符以外的任意字符 \w 匹配字母或数字或下划线 \s 匹配任意的空字 \d 匹配数字 \n 匹配一个换行符 \t

python入门:常用模块—模块,包介绍

一.什么是模块 为了编写可维护的代码,把很多函数分组,分别放到不同的文件里,这样,每个文件包含的代码就相对较少,编程语言采用这种组织方式.在python中,一个.py文件就称之为一个模块. 二.使用模块有什么好处 最大的好处是大大提高了代码的可维护性.其次,编写代码不必从零开始.当一个模块编写完毕,就可以被其他地方引用.经常引用其他模块,包括Python内置的模块和来自第三方的模块 使用模块还可以避免函数名和变量名冲突.每个模块有独立的命名空间 三.模块分类 内置标准模块(又称标准库)执行hel