全局变量

全局变量 python在一个.py文件内部自动添加了一些全局变量

print(vars())  #查看当前的全局变量

执行结果:{'__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x01035A70>, '__cached__': None, '__name__': '__main__', '__spec__': None, '__builtins__': <module 'builtins' (built-in)>, '__doc__': None, '__file__': 'D:/untitled/python5/python5/index.py'}

__builtins__存放内置函数

__doc__ 对.py文件的注释

__package__  当前.py所在的文件夹用 . 划分
导入的其他文件:指定文件文件夹所在包用.划分

__file__ 文件本身自己的路径

__cached__  缓存

__name__ ==' __main__'  只有执行python  主.py文件时 __name__ ==' __main__' 否则 __name__ = 模块名

主文件调用主函数前必须加  if __name__ ==' __main__' 判断

"""
我是index.py文件的注释
"""
print(__doc__)
执行结果:我是index.py文件的注释print(__file__)
执行结果:
D:/untitled/python5/python5/s1.py
import os
import sys
x1 = os.path.dirname(__file__)   # 返回上一级目录
x2 = 'bin'
xin = os.path.join(x1, x2)
sys.path.append(xin)
for i in sys.path:print(i)执行结果:
D:\untitled\python5\lib
D:\untitled
D:\python3.5\python35.zip
D:\python3.5\DLLs
D:\python3.5\lib
D:\python3.5
D:\python3.5\lib\site-packages
D:/untitled/python5/lib\bin

from lib.xx import commons #进入lib文件夹下的xx文件导入commons文件 print(commons.__package__)#文件夹套文件夹用 . 来区分 执行结果: lib.xx 

from lib.xx import commons #进入lib文件夹下的xx文件导入commons文件 print(commons.__cached__) #pyton3里有python2 里没有 用来缓存一个.pyc文件 

#print(__name__) #如果执行当前的主文件.py__name__就等于__main__ 在其他文件或者导入的__name__就是本身文件的名字 from lib.xx import commons print(commons.__name__) 执行结果:__main__ lib.xx.commons

模块:

urllib:request

发起http请求,获取请求返回值

import urllib        #打开一个网址 发送http请求,
from  urllib import requestr = urllib.request.urlopen('http://www.webxml.com.cn//webservices/qqOnlineWebService.asmx/qqCheckOnline?qqCode=78956745465')
result = r.read().decode('utf-8')  #读取打开网址给的返回值 解码成utf-8
print(result)

  

json 和 pickle 

用于序列化的两个模块

  • json,用于字符串 和 python数据类型间进行转换
  • pickle,用于python特有的类型 和 python的数据类型间进行转换

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

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

s = '{"desc":"invilad-citykey","status":1002}' 用于字符串 和 python数据类型间进行转换 字典类型里如果是字符串必须是双引号
l = '[11,22,33,44]'import json   ==字符串, result = json.loads(s)   #loads 将字符串转换为数据基本类型
print(result,type(result))
ss = json.loads(l)
print(ss,type(ss))xin = ['xin','xin1','xin2']
ss = json.dumps(xin)           #将python基本数据类型,转换为字符串
print(ss,type(ss))dic = {'k1': 123,'k2':'v2'}
z = json.dump(dic,open('db','w'))  # 将字符串转换为字典 在字典写入文件
print(z)
r = json.load(open('db','r'))  #将字符串转换为字典读取文件里的字典 类型
print(r,type(r))

requests模块已经将常用的Http请求方法为用户封装完成,用户直接调用其提供的相应方法即可,其中方法的所有参数有:

def request(method, url, **kwargs):"""Constructs and sends a :class:`Request <Request>`.:param method: method for the new :class:`Request` object.:param url: URL for the new :class:`Request` object.:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.:param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.:param json: (optional) json data to send in the body of the :class:`Request`.:param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.:param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.:param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': ('filename', fileobj)}``) for multipart encoding upload.:param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.:param timeout: (optional) How long to wait for the server to send databefore giving up, as a float, or a :ref:`(connect timeout, readtimeout) <timeouts>` tuple.:type timeout: float or tuple:param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.:type allow_redirects: bool:param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.:param verify: (optional) whether the SSL cert will be verified. A CA_BUNDLE path can also be provided. Defaults to ``True``.:param stream: (optional) if ``False``, the response content will be immediately downloaded.:param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.:return: :class:`Response <Response>` object:rtype: requests.ResponseUsage::>>> import requests>>> req = requests.request('GET', 'http://httpbin.org/get')<Response [200]>"""# By using the 'with' statement we are sure the session is closed, thus we# avoid leaving sockets open which can trigger a ResourceWarning in some# cases, and look like a memory leak in others.
    with sessions.Session() as session:return session.request(method=method, url=url, **kwargs)更多参数

View Code

第三方模块
requests  用于发送http请求 (用py模拟浏览器浏览网页)
requests.get ("http://www.baidu.com") 可以发送一个http请求 发送成功接收一个返回值 这个返回值就是个字符串import requests
response = requests.get("http://www.weather.com.cn/adat/sk/101010500.html")
response.encoding = 'utf-8'
xin = response.text   # text 表示返回的内容
print(xin)

XML是实现不同语言或程序之间进行数据交换的协议,XML文件格式如下:

Element类的方法:
# tag       #根节点返回节点的标签名
# attrib    #标签属性
# find      #查找
# iter      #返回匹配到的元素的迭代器     用于找到某一类节点并去循环
# set       #修改属性
# get       #获取属性
#text     返回的内容
ElenmentTree类的方法:
获取xml文件的根节点通过getroot获取根节点
1.tag获取节点的标签名
2.attrib 获取节点的属性
3 text 获取标签的内容

<data><country name="Liechtenstein"><rank updated="yes">2</rank><year>2023</year><gdppc>141100</gdppc><neighbor direction="E" name="Austria" /><neighbor direction="W" name="Switzerland" /></country><country name="Singapore"><rank updated="yes">5</rank><year>2026</year><gdppc>59900</gdppc><neighbor direction="N" name="Malaysia" /></country><country name="Panama"><rank updated="yes">69</rank><year>2026</year><gdppc>13600</gdppc><neighbor direction="W" name="Costa Rica" /><neighbor direction="E" name="Colombia" /></country>
</data>

View Code

1,解析xml

解析xml 有两种解析方式

一种将字符串解析成xml格式

一种直接将文件解析成xml格式

from xml.etree import ElementTree as ET  #利用ElementTree 模块下的xml 方法可以把一个字符串类型的转换为Element类。从而从而利用Element类下面的方法                                             # xml(字符串)解析方式只能读不能写
str_xml = open('db.xml','r').read()   #打开文件,读取xml内容 接收到一个字符串
print(str_xml)
root = ET.XML(str_xml)                    #将字符串解析成xml特殊的对象,toot就是特殊对象 他代指xml文件的节点
print(root)
from xml.etree import ElementTree as ET
root = ET.XML(open('db.xml','r',encoding='utf-8').read())
print(root.tag)   #获取文件的顶层标签
print(dir(root))

另一种方式
tree = ET.parse('db.xml') #直接将文件解析成xml格式 类型是ElementTree
print(tree) root = tree.getroot() #获取到xml文件的节点
print(root)

2,操作xml

xml 格式类型是节点套节点,每一个节点都有不同的功能 以便对当前的节点进行操作

class Element:"""An XML element.This class is the reference implementation of the Element interface.An element's length is its number of subelements.  That means if youwant to check if an element is truly empty, you should check BOTHits length AND its text attribute.The element tag, attribute names, and attribute values can be eitherbytes or strings.*tag* is the element name.  *attrib* is an optional dictionary containingelement attributes. *extra* are additional element attributes given askeyword arguments.Example form:<tag attrib>text<child/>...</tag>tail"""当前节点的标签名tag = None"""The element's name."""当前节点的属性attrib = None"""Dictionary of the element's attributes."""当前节点的内容text = None"""Text before first subelement. This is either a string or the value None.Note that if there is no text, this attribute may be eitherNone or the empty string, depending on the parser."""tail = None"""Text after this element's end tag, but before the next sibling element'sstart tag.  This is either a string or the value None.  Note that if therewas no text, this attribute may be either None or an empty string,depending on the parser."""def __init__(self, tag, attrib={}, **extra):if not isinstance(attrib, dict):raise TypeError("attrib must be dict, not %s" % (attrib.__class__.__name__,))attrib = attrib.copy()attrib.update(extra)self.tag = tagself.attrib = attribself._children = []def __repr__(self):return "<%s %r at %#x>" % (self.__class__.__name__, self.tag, id(self))def makeelement(self, tag, attrib):创建一个新节点"""Create a new element with the same type.*tag* is a string containing the element name.*attrib* is a dictionary containing the element attributes.Do not call this method, use the SubElement factory function instead."""return self.__class__(tag, attrib)def copy(self):"""Return copy of current element.This creates a shallow copy. Subelements will be shared with theoriginal tree."""elem = self.makeelement(self.tag, self.attrib)elem.text = self.textelem.tail = self.tailelem[:] = selfreturn elemdef __len__(self):return len(self._children)def __bool__(self):warnings.warn("The behavior of this method will change in future versions.  ""Use specific 'len(elem)' or 'elem is not None' test instead.",FutureWarning, stacklevel=2)return len(self._children) != 0 # emulate old behaviour, for nowdef __getitem__(self, index):return self._children[index]def __setitem__(self, index, element):# if isinstance(index, slice):#     for elt in element:#         assert iselement(elt)# else:#     assert iselement(element)self._children[index] = elementdef __delitem__(self, index):del self._children[index]def append(self, subelement):为当前节点追加一个子节点"""Add *subelement* to the end of this element.The new element will appear in document order after the last existingsubelement (or directly after the text, if it's the first subelement),but before the end tag for this element."""self._assert_is_element(subelement)self._children.append(subelement)def extend(self, elements):为当前节点扩展 n 个子节点"""Append subelements from a sequence.*elements* is a sequence with zero or more elements."""for element in elements:self._assert_is_element(element)self._children.extend(elements)def insert(self, index, subelement):在当前节点的子节点中插入某个节点,即:为当前节点创建子节点,然后插入指定位置"""Insert *subelement* at position *index*."""self._assert_is_element(subelement)self._children.insert(index, subelement)def _assert_is_element(self, e):# Need to refer to the actual Python implementation, not the# shadowing C implementation.if not isinstance(e, _Element_Py):raise TypeError('expected an Element, not %s' % type(e).__name__)def remove(self, subelement):在当前节点在子节点中删除某个节点"""Remove matching subelement.Unlike the find methods, this method compares elements based onidentity, NOT ON tag value or contents.  To remove subelements byother means, the easiest way is to use a list comprehension toselect what elements to keep, and then use slice assignment to updatethe parent element.ValueError is raised if a matching element could not be found."""# assert iselement(element)
        self._children.remove(subelement)def find(self, path, namespaces=None):获取第一个寻找到的子节点"""Find first matching element by tag name or path.*path* is a string having either an element tag or an XPath,*namespaces* is an optional mapping from namespace prefix to full name.Return the first matching element, or None if no element was found."""return ElementPath.find(self, path, namespaces)def findtext(self, path, default=None, namespaces=None):获取第一个寻找到的子节点的内容"""Find text for first matching element by tag name or path.*path* is a string having either an element tag or an XPath,*default* is the value to return if the element was not found,*namespaces* is an optional mapping from namespace prefix to full name.Return text content of first matching element, or default value ifnone was found.  Note that if an element is found having no textcontent, the empty string is returned."""return ElementPath.findtext(self, path, default, namespaces)def findall(self, path, namespaces=None):获取所有的子节点"""Find all matching subelements by tag name or path.*path* is a string having either an element tag or an XPath,*namespaces* is an optional mapping from namespace prefix to full name.Returns list containing all matching elements in document order."""return ElementPath.findall(self, path, namespaces)def iterfind(self, path, namespaces=None):获取所有指定的节点,并创建一个迭代器(可以被for循环)"""Find all matching subelements by tag name or path.*path* is a string having either an element tag or an XPath,*namespaces* is an optional mapping from namespace prefix to full name.Return an iterable yielding all matching elements in document order."""return ElementPath.iterfind(self, path, namespaces)def clear(self):清空节点"""Reset element.This function removes all subelements, clears all attributes, and setsthe text and tail attributes to None."""self.attrib.clear()self._children = []self.text = self.tail = Nonedef get(self, key, default=None):获取当前节点的属性值"""Get element attribute.Equivalent to attrib.get, but some implementations may handle this abit more efficiently.  *key* is what attribute to look for, and*default* is what to return if the attribute was not found.Returns a string containing the attribute value, or the default ifattribute was not found."""return self.attrib.get(key, default)def set(self, key, value):为当前节点设置属性值"""Set element attribute.Equivalent to attrib[key] = value, but some implementations may handlethis a bit more efficiently.  *key* is what attribute to set, and*value* is the attribute value to set it to."""self.attrib[key] = valuedef keys(self):获取当前节点的所有属性的 key"""Get list of attribute names.Names are returned in an arbitrary order, just like an ordinaryPython dict.  Equivalent to attrib.keys()"""return self.attrib.keys()def items(self):获取当前节点的所有属性值,每个属性都是一个键值对"""Get element attributes as a sequence.The attributes are returned in arbitrary order.  Equivalent toattrib.items().Return a list of (name, value) tuples."""return self.attrib.items()def iter(self, tag=None):在当前节点的子孙中根据节点名称寻找所有指定的节点,并返回一个迭代器(可以被for循环)。"""Create tree iterator.The iterator loops over the element and all subelements in documentorder, returning all elements with a matching tag.If the tree structure is modified during iteration, new or removedelements may or may not be included.  To get a stable set, use thelist() function on the iterator, and loop over the resulting list.*tag* is what tags to look for (default is to return all elements)Return an iterator containing all the matching elements."""if tag == "*":tag = Noneif tag is None or self.tag == tag:yield selffor e in self._children:yield from e.iter(tag)# compatibilitydef getiterator(self, tag=None):# Change for a DeprecationWarning in 1.4
        warnings.warn("This method will be removed in future versions.  ""Use 'elem.iter()' or 'list(elem.iter())' instead.",PendingDeprecationWarning, stacklevel=2)return list(self.iter(tag))def itertext(self):在当前节点的子孙中根据节点名称寻找所有指定的节点的内容,并返回一个迭代器(可以被for循环)。"""Create text iterator.The iterator loops over the element and all subelements in documentorder, returning all inner text."""tag = self.tagif not isinstance(tag, str) and tag is not None:returnif self.text:yield self.textfor e in self:yield from e.itertext()if e.tail:yield e.tail

View Code

由于 每个节点 都具有以上的方法,并且在上一步骤中解析时均得到了root(xml文件的根节点),so   可以利用以上方法进行操作xml文件。
遍历XML文档的所有内容

from xml.etree import ElementTree as ET
root = ET.XML(open('db.xml','r',encoding='utf-8').read())
print(root.tag)   #获取文件的顶层标签
for node in root:   循环遍历xml文档的第二层节点print(node.tag,node.attrib)  #获取标签名,及属性for i in node:       # 循环遍历第三层print(i.tag,i.text)  #循环遍历xml文件的第三层标签名和内容

遍历xml指定的节点内容

指定xml文件的节点内容
from xml.etree import ElementTree as ET
root = ET.XML(open('db.xml','r',encoding='utf-8').read())
print(root.tag)   #获取文件的顶层标签
for node in root:                            print(node.tag,node.attrib,node.find('year').text)  #获取指定的的节点的标签名及内容from xml.etree import ElementTree as ET
root = ET.XML(open('db.xml','r',encoding='utf-8').read())
print(root.tag)   #获取文件的顶层标签
for node in root:print(node.tag,node.attrib,node.find('rank').text)  #获取指定的的节点的标签名及内容

3,修改节点内容

由于修改的节点时,均是在内存中进行,其不会影响文件中的内容。所以,如果想要修改,则需要重新将内存中的内容写到文件。

# 进入xml文件下的etree文件导入ElementTree模块 将别名赋给ET
from xml.etree import ElementTree as ET
str_xml = open('db.xml','r').read() #打开文件读取xml文件内容
root = ET.XML(str_xml)   #将接受到的字符串解析成xml格式的特殊对象,
print(root)     #获取顶层的标签
for node in root.iter('year'): # 循环遍历所有的year节点new_year = int(node.text)+1   #并且将year节点的内容每次有加一node.text = str(new_year)node.set('name','kaixin')     #给当前节点设置属性node.set('age','20')         del node.attrib['name']      #删除当前节点下的name属性

tree = ET.ElementTree(root)
tree.write('xxx.xml',encoding='utf-8')  #写入并保存文件

另一种方式  打开文件并解析成xml格式
from xml.etree import ElementTree as ETtree = ET.parse('db.xml')    #直接解析xml文件
root = tree.getroot()
print(root.tag)
for node in root.iter('year'):new_year = int(node.text) + 1node.text = str(new_year)node.set('name','kaixin')node.set('age','20')del node.attrib['name']tree.write('zzz.xml',encoding='utf-8')

删除节点

from xml.etree import ElementTree as ET
tree = ET.parse('db.xml')  #打开xml 文件
root = tree.getroot()      #获取到根节点
for country in root.findall('country'):  #循环遍历所有的 countrtrank = int(country.find('rank').text)   #获取每一个country节点下的节点内容if rank > 50:  # 只要rank大于50root.remove(country)    #删除指定的country节点内容
tree.write('xxx.xml',encoding='utf-8')

创建节点
tree

1 ElementTree 类创建 ElementTree(xxx)

root Element类创建的对象

# print(root.tag) # print(root.attrib)

2 getroot() 获取xml跟节点

3. write() 内存中的xml写入文件中

from xml.etree import ElementTree as ET
tree = ET.parse('db.xml')  #直接解析xml文件# tree, 用ElementTree 创建的#ElemenTree(xxx)创建   getroot ()获取xml根节点 weite()内存中的xml写入文件
root = tree.getroot()         #获取xml文件的根节点,Element类型
print(root.tag)
# #root Element类创建的对象
#  创建节点
son = root.makeelement('tt',{'kk':'vv'})   标签名 及属性
s = son.makeelement('tt',{'kk':'123456'})
son.append(s)
root.append(son)
tree.write('db.xml.xml')

from xml.etree import ElementTree as ET
tree = ET.parse('db.xml')  #直接解析xml文件
root = tree.getroot()         #获取xml文件的根节点,Element类型
son = ET.Element('PP',{'kk':'vv'})   直接通过Element 方法创建节点
ele2 = ET.Element('pp',{'kk':'123455'})
son.append(ele2)   将第二层的节点追加到第一层的节点下
root.append(son)   将第一层的节点加到根节点下
tree.write('db.xml')  tree。write 将内存中的xml写入文件

configparser用于处理特定格式的文件,其本质上是利用open来操作文件。

import configparser  #处理将有效地读取这个配置文件数据

con = configparser.ConfigParser() #con 对象的read功能,打开文件读取文件,放进内容
con.read('in',encoding='utf-8')
# con对象中的sections 内存中寻找所有的[xxx]
xin = con.sections()   #获取所有的节点
print(xin)ret = con.items('guokaixin')   #获取所有的键值对
print(ret)ret = con.options('guokaixin')   #获取指定节点下的所有的键
print(ret)ret = con.get('guokaixin','age')  #获取指定节点下的指定键的值
print(ret)
ret1 = con.getint('guokaixin','age')
print(ret1)
ret2 = con.getfloat('guokaixin','age')
print(ret2)
ret3 = con.getboolean('guokaixin','age')
print(ret3)has_sec = con.has_section('guokaixin')   #检查节点是否存在
print(has_sec)
s = con.add_section('xinxin')   #添加节点
a = con.write(open('in','w'))
print(s)
print(a)s = con.remove_section('xinxin')  #删除节点
a = con.write(open('in','w'))
print(s)
print(a)检查、删除、添加节点import configparser
a = configparser.ConfigParser()
s = a.read('xxxooo', encoding='utf-8')
print(s)
# 检查
has_opt = a.has_option('section1', 'k1')
print(has_opt)
# 删除
zz = a.remove_option('section1', 'k1')
cc = a.write(open('xxxooo', 'w'))
print(zz)
print(cc)
# 设置
zz = a.set('section1', 'k10', "123")
cc = a.write(open('xxxooo', 'w'))
print(zz)
print(cc)

由于原生保存的XML时默认无缩进,如果想要设置缩进的话, 需要修改保存方式:

from xml.etree import ElementTree as ET
from xml.dom import minidomdef MyWrite(root,filr_path):rough_string = ET.tostring(root,'utf-8')reparsed = minidom.parseString(rough_string)new_str = reparsed.toprettyxml(indent='\t')  #加了缩进的字符串f = open(filr_path,'w',encoding='utf-8')f.write(new_str)f.close()

  shutil

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

z = shutil.copyfileobj(open('zzz','r'),open('xxx.xml','w'))
print(z)     #将内容拷贝到另一个文件中

z = shutil.copyfile('zz.py','xx.py')
print(z)          #拷贝文件

z = shutil.copymode('zz.py','xx.py')
print(z)      #拷贝加权限,内容用户不变原来是什么还是什么
z = shutil.copystat('zz.py','xx.py')
print(z)     # 拷贝状态的信息,包括:mode bits, atime, mtime, flags
z = shutil.copy('zz.py','xx.py')
print(z)     # 拷贝文件和权限
z = shutil.copy2('zz.py','xx.py')
print(z)      #拷贝文件和状态信息
 z = shutil.copytree('zz.py','xx.py',ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))
print(z)  #递归的去拷贝文件夹

z = shutil.move('asd','in')
print(z) #递归的去移动文件,它类似mv命令,其实就是重命名。
z = shutil.rmtree('zz.py')
print(z) #递归的去删除文件

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

import zipfile# z = zipfile.ZipFile('laxi.zip','w')
# z.write('in')
# z.write('xo.xml')
# z.close()import zipfile
z = zipfile.ZipFile('spiders.zip','r')
z.extractall()
z.close()

logging:

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

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=logging.INFO)对于等级:
"""
CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0
"""logging.critical('ssssssssssss')
logging.fatal('zzzzzzzzzzzz')
logging.error('ssssssssss')
logging.warning('ssssss')
logging.info('ssssssssss')
logging.debug('xxxxxxxxxxxx')
logging.log(logging.INFO,'333')
只有大于当前日志等级的操作才会被记录。

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

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

最简单的用法

看一下这几个日志级别分别代表什么意思

Level When it’s used
DEBUG Detailed information, typically of interest only when diagnosing problems.
INFO Confirmation that things are working as expected.
WARNING An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected.
ERROR Due to a more serious problem, the software has not been able to perform some function.
CRITICAL A serious error, indicating that the program itself may be unable to continue running.

  

如果想把日志写到文件里,也很简单

1
2
3
4
5
6
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')

其中下面这句中的level=loggin.INFO意思是,把日志纪录级别设置为INFO,也就是说,只有比日志是INFO或比INFO级别更高 的日志才会被纪录到文件里,在这个例子, 第一条日志是不会被纪录的,如果希望纪录debug的日志,那把日志级别改成DEBUG就行了。

1
logging.basicConfig(filename='example.log',level=logging.INFO)

感觉上面的日志格式忘记加上时间啦,日志不知道时间怎么行呢,下面就来加上!

1
2
3
4
5
6
import logging
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
logging.warning('is when this event was logged.')
#输出
12/12/2010 11:46:36 AM is when this event was logged.

  

如果想同时把log打印在屏幕和文件日志里,就需要了解一点复杂的知识 了

The logging library takes a modular approach and offers several categories of components: loggers, handlers, filters, and formatters.

  • Loggers expose the interface that application code directly uses.
  • Handlers send the log records (created by loggers) to the appropriate destination.
  • Filters provide a finer grained facility for determining which log records to output.
  • Formatters specify the layout of log records in the final output

 

转载于:https://www.cnblogs.com/guokaixin/p/5525448.html

python模块介绍二。相关推荐

  1. [ 转]Python模块(二)import和from...import的区别

    Python模块(二)import和from...import的区别 听语音 原创 | 浏览:2975 | 更新:2018-04-02 13:02 | 标签:PYTHON 1 2 3 4 5 6 7 ...

  2. python模块介绍-locustio:性能测试工具locustio

    转自:http://automationtesting.sinaapp.com/blog/m_locustio_doc python测试文章 http://weibo.com/cizhenshi?is ...

  3. python模块介绍- xlwt 创建xls文件(excel)

    python模块介绍- xlwt 创建xls文件(excel) 2013-06-24磁针石 #承接软件自动化实施与培训等gtalk:ouyangchongwu#gmail.comqq 37391319 ...

  4. Python模块之二:Python3 常用模块总结

    Python模块之二:Python3 常用模块总结 一.random模块 提供一些随机数获取的相关方法 1.常用方法 1.random():获取[0.0,1.0)范围内的浮点数 2.randint(a ...

  5. python模块介绍-gevent介绍:基于协程的网络库

    2019独角兽企业重金招聘Python工程师标准>>> python模块介绍-gevent介绍:基于协程的网络库 介绍 gevent是基于协程的Python网络库.特点: 基于lib ...

  6. python实现二维码识别软件_OpenCV和Zbar两个Python模块实现二维码和条形码识别

    在我们的日常生活中,处处可见条形码和二维码. 在以前,我们去逛书店时,或者你现在随手拿起你身边的一本书,你肯定能看到书本的封页后面印有一排黑色线条组成的标签,也就是条形码:你去你们学校的自助机上借书还 ...

  7. Python模块介绍(如何安装、使用)

    Python不仅灵活方便,而且功能强大,丰富的标准库更是让Python成为"自带电池"的编程语言. 安装其他模块 python自带的模块显然不能满足我们的需求,我们可以下载安装其他 ...

  8. python模块介绍- SocketServer 网络服务框架

    转载自http://my.oschina.net/u/1433482/blog/190612 摘要 SocketServer简化了网络服务器的编写.它有4个类:TCPServer,UDPServer, ...

  9. 扩展Python模块系列(二)----一个简单的例子

    本节使用一个简单的例子引出Python C/C++ API的详细使用方法.针对的是CPython的解释器. 目标:创建一个Python内建模块test,提供一个功能函数distance, 计算空间中两 ...

  10. 【Python从零到壹】Python模块介绍与使用

    文章目录 模块的相关概念 1. 什么是模块 2. 使用模块的好处 模块的使用 1. 自定义模块 a) 方法一: 导入模块: b) 方法二 c) 导入自己的模块 Python中的包 1. 包的介绍 2. ...

最新文章

  1. “记住密码“功能的正确设计
  2. python缩进的用途和使用方法_如何用Python减少循环层次和缩进的技巧
  3. docker安装最新版Jenkins:拉取镜像/创建容器
  4. jsp在mysql中删除数据_如何在jsp页面中删除数据库中的数据
  5. Michael Dell承诺打造新的EMC/戴尔/VMware工程技术系统
  6. Coolite ComboBox绑定方式
  7. sticky-footer布局
  8. 几个C#控件出现闪烁的问题的解决方案(转)
  9. ipq806X的猜想
  10. 第二章 Jsp基本语法
  11. fastjson list转json
  12. 基于Java+Swing实现坦克大战游戏
  13. 碰撞检测——碰撞器和物理材质
  14. 杨焘鸣:潜意识的特性
  15. 十分钟看懂时序数据库(I)-存储
  16. 重装战姬服务器正在维护,《重装战姬》4月23日更新维护公告
  17. ubuntu WPS字体缺失 解决方法
  18. 磨金石教育摄影技能干货分享|人物系列摄影作品欣赏
  19. Linux Centos8 安装Minio开机启动并Nginx代理访问
  20. 满庭芳国色 高清剪图 桃红 上

热门文章

  1. python 系统管理_python系统管理
  2. Github Projects 项目管理 怎么用
  3. CI 什么是构建 gradle
  4. java 弹框_java弹框
  5. java configuration类_使用@Configuration编写自定义配置类
  6. mysql 字符串搜_Mysql搜索字符串
  7. trie树 java 开源_用于实现Trie的内存java应用程序中的最佳开源
  8. datatable自定义搜索和导出按钮并解决在后端分页无法导出全部数据的问题
  9. ubuntu20.4安装 mariadb 最新版
  10. Logstash 日志搜集处理框架 安装配置