Python之logging,os,sys,random和string模块简析
1.logging模块
#!/usr/bin/env python
# -*- coding:utf8 -*-
# @Time : 2017/11/10 10:00
# @Author : hantong
# @File : log.py
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='.log', filemode='w')
#此参数很长,建议拷贝下来使用时直接粘贴,包含日志格式的设定,日志信息写入文件等信息
logger = logging.getLogger(__name__)
#打印时时的log信息,写入日志时清空之前的内容
logging.debug('this is debug message')
logging.info('this is info message')
logging.warning('this is warning message')
logging.error('this is error message')
logging.critical('this is critical message')
#以上是日志的几个级别
代码输出为空,但是建立了一个logging.log的文件,并且日志写入此文件
2.os模块
#!/usr/bin/env python
# -*- coding:utf8 -*-
# @Time : 2017/11/10 14:10
# @Author : hantong
# @File : os_test.py
import os
# print(os.name)
#windows系统显示的是‘nt’,linux系统显示的是‘posix’
# cont = os.popen('ipconfig').read()
# print(cont)
#查看windows系统网卡信息,由于系统语言格式问题,显示出来乱码
print(os.listdir('.'))
#查看当前目录文件
print(os.getcwd())
#查看当前路径
print(os.listdir(os.getcwd()))
os.chdir(r'E:\Xshell 5')
#切换目录到E:\Xshell5
print(os.getcwd())
#查看是否切换成功
# os.mkdir('txt1111')
#新建一个文件名为txt1111的文件
# os.remove('txt111')
#删除一个文件
print(os.linesep)
#打印操作系统的分隔符
if not os.path.exists('txt11'):
#os.path.exists('txt11')检查是否存在txt11这个文件
os.makedirs('txt11')
#新建txt11文件,连同目录一起建立
#os.makedirs()
else:
print('txt11 directory is ok!')
path = os.path.join(os.getcwd(),'abc')
#拼接目录
print(path)
print(os.path.dirname(r'E:\Xshell 5'))
#查看根目录
执行结果:
['.idea', '.log', '1.txt', '2.txt', 'buer.py', 'class.py', 'class2.py', 'class3.py', 'class4.py', 'class5.py', 'command_test.py', 'convert.py', 'daetime2.py', 'datetime.py', 'def.py', 'dict.py', 'except.py', 'file.py', 'float.py', 'for.py', 'func.py', 'func2.py', 'genarator.py', 'help.py', 'hhh.py', 'if.py', 'lianxi.py', 'list', 'list.py', 'list.txt', 'log.py', 'myapp.log', 'os_test.py', 'os_test.pyc', 'revise.py', 'str.py', 'sys_test.py', 'test.py', 'test.pyc', 'test2.py', 'test3.py', 'test4.py', 'threed_week.py', 'tuple.py', 'txt', 'txt3', 'while.py']
E:\Ǩ������\python\pycharm2017pjb\PycharmProjects
['.idea', '.log', '1.txt', '2.txt', 'buer.py', 'class.py', 'class2.py', 'class3.py', 'class4.py', 'class5.py', 'command_test.py', 'convert.py', 'daetime2.py', 'datetime.py', 'def.py', 'dict.py', 'except.py', 'file.py', 'float.py', 'for.py', 'func.py', 'func2.py', 'genarator.py', 'help.py', 'hhh.py', 'if.py', 'lianxi.py', 'list', 'list.py', 'list.txt', 'log.py', 'myapp.log', 'os_test.py', 'os_test.pyc', 'revise.py', 'str.py', 'sys_test.py', 'test.py', 'test.pyc', 'test2.py', 'test3.py', 'test4.py', 'threed_week.py', 'tuple.py', 'txt', 'txt3', 'while.py']
E:\Xshell 5
txt11 directory is ok!
E:\Xshell 5\abc
E:\
#上面乱码部分是中文导致的
3.commmands模块
#此命令必须在linux系统上才能执行
#!/usr/bin/env python
#-*-coding:utf-8 -*-
#只能在linux下使用
import commands
cmd = 'ls /home'
result = commands.getoutput(cmd)
print(type(result))
print(result)
#commands.getoutput的返回值只有返回结果,没法进行判断执行结果是否正常
cmd1 = 'ps -ds|fial'
status,result = commands.getstatusoutput(cmd1)
print(type(result))
print(result)
print(type(status))
print(status)
#commands.getstatusoutput的返回值是一个tuple类型
执行结果不再贴出来,因为太长
4.sys模块
sys.argv 命令行参数List,第一个元素是程序本身路径
sys.exit(n) 退出程序,正常退出时exit(0)
sys.hexversion 获取Python解释程序的版本值,16进制格式如:0x020403F0
sys.version 获取Python解释程序的版本信息
sys.modules 返回系统导入的模块字段,key是模块名,value是模块
sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform 返回操作系统平台名称
sys.stdout 标准输出
sys.stdin 标准输入
sys.stderr 错误输出
5.random,string 模块
#!/usr/bin/env python # -*- coding:utf8 -*- # @Time : 2018/4/24 20:36 # @Author : hantong # @File : 20180424.py import logging import os import random import string import sys print(os.name) print(os.listdir()) # os.makedirs('1.txt') print(os.getcwd()) # os.write('2.txt','kkkkllll') logging.basicConfig(level=logging.DEBUG) print(random.randint(1,100)) #随机在1-100之间生成两个数字 print(random.randint(1,1000000)) #随机生成六位数字验证码 print(sys.path.append('0')) print(string.ascii_letters) #打印字母大小写 print(string.ascii_lowercase) #打印小写字母 print(string.ascii_uppercase) #打印大写字母 print(string.digits)#打印数字 print(string.printable)#打印数字字母大小写和特殊字符 print(string.octdigits) #打印数字0-7 #练习题 随机生成数字和字母组合六位验证码 print("".join(random.sample(string.ascii_lowercase+string.digits,6))) # print(random.sample([1,2,3,4,5,6,6,7,7,7,8,9,0],2))
执行结果:
97
762455
None
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
01234567
7gesi1