python自动化开发-5b

python的常用模块(续)

  time和datetime模块

  time模块和datetime模块举例

    例子:获取当前时间      

1 import datetime,time
2 now = time.strftime("%Y-%m-%d %H:%M:%S")
3 print(now)
4 now = datetime.datetime.now()
5 print(now)
View Code

运行结果:

  2017-02-21 09:20:55
  2017-02-21 09:20:55.474040

      

    例子:按照指定格式显示      

1 #按指定格式显示时间
2 import time
3 t = time.localtime()
4 print(time.strftime("%Y-%m-%d %H:%M:%S",t))
View Code

运行结果:2017-02-21 09:02:29

     例子:常见结构化显示时间,与上面的代码等价      

1 import time
2 t = time.localtime()
3 print(time.strftime("%Y-%m-%d %X"))
View Code

运行结果:2017-02-21 09:08:25

   random模块

     python的random模块用于生成随机数。

     random模块的常用函数和举例

       random.random()用于生成一个0到1的随机数。

       例子:        

1 import random
2 res=random.random()
3 print(res)
View Code

运行结果:0.4416841951236985

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

      例子:      

1 import random
2 res=random.randint(1,5)
3 print(res)
View Code

运行结果:2

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

      例子1:      

1 import random
2 res=random.randrange(1,10,2)
3 print(res)
View Code

运行结果:7

      例子2:        

1 import random
2 res=random.randrange(1,10)
3 print(res)
View Code

运行结果:3

   OS模块

  在python的开发过程中,少不了和文件、目录打交道,这是就离不了os模块,它提供对操作系统进行调用的接口。os模块包含普遍的操作系统功能,与具体的平台无关。OS模块里的函数比较多,在此只列举常用的模块。

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

      例子:       

1 import os
2 res=os.getcwd()
3 print(res)
View Code

运行结果:E:S16day5

    os.system():运行shell命令,直接显示。

  sys模块

  sys.argv:相对来说,比较常用。命令行参数List,第一个元素是程序本身路径。

  logging模块

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

    默认情况下,logging将日志打印到屏幕,日志级别为WARNING

    logging日志模块举例 

    1.打印日志到屏幕     

1 import logging
2 
3 logging.debug('RYB,this is debug message')
4 logging.info('RYB,this is info message')
5 logging.warning('RYB,this is warning message')
View Code

运行结果:  WARNING:root:RYB,this is warning message

      2.通过logging.basicConfig函数对日志的输出格式及方式做相关配置      

 1 import logging
 2 logging.basicConfig(level=logging.DEBUG,
 3                 format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
 4                 datefmt='%a, %d %b %Y %H:%M:%S',
 5                 filename='myapp.log',
 6                 filemode='w')
 7 
 8 logging.debug('This is debug message')
 9 logging.info('This is info message')
10 logging.warning('This is warning message')
View Code

运行结果:生成文件myapp.log

  myapp.log内容如下:

Tue, 21 Feb 2017 11:08:08 test1.py[line:128] DEBUG This is debug message
Tue, 21 Feb 2017 11:08:08 test1.py[line:129] INFO This is info message
Tue, 21 Feb 2017 11:08:08 test1.py[line:130] WARNING This is warning message 


logging.basicConfig函数各参数:
filename: 指定日志文件名
filemode: 和file函数意义相同,指定日志文件的打开模式,'w'或'a'
format: 指定输出的格式和内容,format可以输出很多有用信息,如上例所示:
 %(levelno)s: 打印日志级别的数值
 %(levelname)s: 打印日志级别名称
 %(pathname)s: 打印当前执行程序的路径,其实就是sys.argv[0]
 %(filename)s: 打印当前执行程序名
 %(funcName)s: 打印日志的当前函数
 %(lineno)d: 打印日志的当前行号
 %(asctime)s: 打印日志的时间
 %(thread)d: 打印线程ID
 %(threadName)s: 打印线程名称
 %(process)d: 打印进程ID
 %(message)s: 打印日志信息
datefmt: 指定时间格式,同time.strftime()
level: 设置日志级别,默认为logging.WARNING
stream: 指定将日志的输出流,可以指定输出到sys.stderr,sys.stdout或者文件,默认输出到sys.stderr,当stream和filename同时指定时,stream被忽略

    3.把日志同时输出到文件和屏幕      
 1 import logging
 2 
 3 logging.basicConfig(level=logging.DEBUG,
 4                 format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
 5                 datefmt='%a, %d %b %Y %H:%M:%S',
 6                 filename='myapp.log',
 7                 filemode='w')
 8 
 9 
10 #定义一个StreamHandler,将INFO级别或更高的日志信息打印到标准错误,并将其添加到当前的日志处理对象#
11 console = logging.StreamHandler()
12 console.setLevel(logging.INFO)
13 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
14 console.setFormatter(formatter)
15 logging.getLogger('').addHandler(console)
16 
17 
18 logging.debug('This is debug message')
19 logging.info('This is info message')
20 logging.warning('This is warning message')
View Code
运行结果:在屏幕上打印如下内容:     

root : INFO This is info message
root : WARNING This is warning message

在文件myapp.log里打印如下内容:

Tue, 21 Feb 2017 19:34:18 test2.py[line:21] DEBUG This is debug message
Tue, 21 Feb 2017 19:34:18 test2.py[line:22] INFO This is info message
Tue, 21 Feb 2017 19:34:18 test2.py[line:23] WARNING This is warning message
原文地址:https://www.cnblogs.com/renyongbin/p/6422360.html