码迷,mamicode.com
首页 > 编程语言 > 详细

python内置模块

时间:2018-04-25 21:01:07      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:dem   table   not   case   eve   stderr   函数返回   忽略   创建   

 

logging模块

日志一共分为五个等级,从低到高依次是debug、info、warning、error、critical
debug: 详细的所有信息
info:     确认一个按期运行
warning:一些意想不到的事情发生了,或者一些问题在不久的将来会出现
error:   更严重的问题,软件没能执行一些功能
critical: 一个严重的错误,这表明程序本身可能无法继续运行

 将日志输出到控制台

import logging
logger = logging.debug("this is debug")
logger = logging.info("this is info")
logger = logging.warning("this is warning")
logger = logging.error("this is error")
logger = logging.critical("this is critical")
结果:
WARNING:root:this is warning
ERROR:root:this is error
CRITICAL:root:this is critical

 

使用logging.basicConfig()设置日志的一些相关信息,如级别、格式等。

import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.debug("this is debug")
logger = logging.info("this is info")
logger = logging.warning("this is warning")
logger = logging.error("this is error")
logger = logging.critical("this is critical")
结果:
DEBUG:root:this is debug
INFO:root:this is info
WARNING:root:this is warning
ERROR:root:this is error
CRITICAL:root:this is critical

 

设置日志格式,输入到指定文件

import logging
logging.basicConfig(level=logging.DEBUG, format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s,datefmt= %Y/%m/%d %H:%M:%S, filename=1.log, filemode=w)
logger = logging.getLogger(__name__)  # 创建一个日志对象
logging.debug(This is debug message)
logging.info(This is info message)
logging.warning(This is warning message)

在当前文件夹里面生成了一个名为1.log的文件,文件格式如下:

 2018/04/25 08:39:46 demo1.py[line:10] DEBUG This is debug message
 2018/04/25 08:39:46 demo1.py[line:11] INFO This is info message
 2018/04/25 08:39:46 demo1.py[line:12] WARNING This is warning message

上面主要是通过logging.basicConfig()函数来实现的,它的相关参数如下:

level: 设置日志级别,默认为logging.WARNING
filename: 指定日志文件名。
filemode: 和file函数意义相同,指定日志文件的打开模式,wa
format: 指定输出的格式和内容,format可以输出很多有用信息,如上例所示:
%(levelname)s: 打印日志级别名称
%(filename)s: 打印当前执行程序名
%(funcName)s: 打印日志的当前函数
%(lineno)d: 打印日志的当前行号
%(asctime)s: 打印日志的时间
%(thread)d: 打印线程ID
%(process)d: 打印进程ID
%(message)s: 打印日志信息
datefmt: 指定时间格式,同time.strftime()
stream: 指定将日志的输出流,可以指定输出到sys.stderr,sys.stdout或者文件,默认输出到sys.stderr,当stream和filename同时指定时,stream被忽略
logging.getLogger([name]):创建一个日志对象

 

os模块

import os
os.system(cmd) # 执行系统命令,但是没有返回结果
‘‘‘
nt     为windows系统
posix  为unix系统
‘‘‘

如果需要对结果进行处理,我们可以这样做:

result = os.popen(cmd)
result.read()

为了让一段代码,既可以在windows下运行,又可以在linux下运行。

import os
if os.name == "nt":
    cmd = "ipconfig"
elif os.name == "posix":
    cmd = "ifconfig"
os.system(cmd)

相关用法:

os.listdir(".")   # 列出当前目录
os.chdir("/tmp")  # 改变目录
os.getcwd()       # 获取当前路径
os.mkdir("test")  # 创建目录
os.rmdir("test")  # 删除目录
os.rename("test","test1")  #重命名
os.linesep        # 给出当前平台使用的行终止符
# windows  换行符 \n\r
# linux 换行符 \n

判断一个文件是否存在,如果不存在,就创建该目录

import os
if not os.path.exists("test"):
    os.mkdir("test")

查看绝对路径

os.path.abspath("test")

 

random模块

random()函数返回一个随机生成的实数。

import random
# 在1-100内生成一个随机数
print(random.randint(1,100))
# 在1-100内生成一个随机数,每隔两个数取一个数
print(random.randrange(1,100,2))
# [1, 2, 3, 4, 5, 6, 7]中随机取出2个数
print(random.sample([1, 2, 3, 4, 5, 6, 7], 2))

抛掷一枚骰子1000次,统计每一面出现的次数:

import random
class NumberCount(object):
    def __init__(self):
        self.number1 = 0
        self.number2 = 0
        self.number3 = 0
        self.number4 = 0
        self.number5 = 0
        self.number6 = 0
    def count(self):
        for i in range(1,1001):
            number = random.randint(1,6)
            if number == 1:
                self.number1 += 1
            if number == 2:
                self.number2 += 1
            if number == 3:
                self.number3 += 1
            if number == 4:
                self.number4 += 1
            if number == 5:
                self.number5 += 1
            if number == 6:
                self.number6 += 1
    def getResult(self):
        print("1出现的次数是:{0}".format(self.number1))
        print("2出现的次数是:{0}".format(self.number2))
        print("3出现的次数是:{0}".format(self.number3))
        print("4出现的次数是:{0}".format(self.number4))
        print("5出现的次数是:{0}".format(self.number5))
        print("6出现的次数是:{0}".format(self.number6))
if __name__ == "__main__":
    numberCount = NumberCount()
    numberCount.count()
    numberCount.getResult()

 

string模块

import string

print(string.ascii_letters) # 生成所有的字母包括大小写
# abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
print(string.digits)  # 生成所有的数字
# 0123456789
print(string.ascii_lowercase)  # 生成所有的小写字母
# abcdefghijklmnopqrstuvwxyz
print(string.ascii_uppercase)  # 生成所有的大写字母
# ABCDEFGHIJKLMNOPQRSTUVWXYZ
print(string.printable)        # 生成所有可打印字符
# 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&‘()*+,-./:;<=>?@[\]^_`{|}~
print(string.punctuation)      # 申城所有特殊字符
# !"#$%&‘()*+,-./:;<=>?@[\]^_`{|}~
print(string.hexdigits)  # 生成所有十六进制的字符串
# 0123456789abcdefABCDEF

生成随机六位验证码

print("".join(random.sample(string.ascii_letters + string.digits, 6)))

 

python内置模块

标签:dem   table   not   case   eve   stderr   函数返回   忽略   创建   

原文地址:https://www.cnblogs.com/yangjian319/p/8946967.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!