python笔记1

来源:互联网 发布:绘画截屏软件 编辑:程序博客网 时间:2024/05/21 21:40
1.python logging
方法一:
import logging
logging.basicConfig(level=logging.DEBUG,
     format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
     datefmt='%a,%d %b %Y %H:%M:%S',
     filename='/tmp/test.log',
     filemode='w')
  
方法二:  
logger = logging.getLogger()
fh = logging.FileHandler('test.log')
ch = logging.StreamHandler()
formatter = logging.Farmatter('%(asctime)s -%(name)s - %(levelname)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
logger.addHandler(fh)
logger.addHandler(ch)
logger.setLevel(Logging.DEBUG)
logger.debug('logger debug message')

2.配置文件 configparser

#创建
import configparser
config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval':'45','Compression':'yes','CompressionLevel':'9'}
config['bitbucket.org']={}
config['bitbucket.org']['User']='hg'
config['topsecret.server.con']={}
topsecret=config['topsecret.server.com']
topsecret['Host Port']='50022'
topsecret['ForwardX11']='no'
config['DEFAULT']['ForwardX11']='yes'
with open('example.ini', 'w') as configfile:
 config.write(configfile)
 
#读取
import configparser
config = configparser.ConfigParser()
config.read('example.ini')
print(config.sections())
print(config.defaults())
print(config['bitbucket.org']['User'])
for key in config['bitbucket.org']: #打印包括了DEFAULT
 print(key)
#删除
config.remove_section('topsecret.server.com')
config.write(open('a.cfg', "w")) #保存到另外一个文件里
config.remove_option('topsecret.server.com', 'user')
config.write(open('example.ini', "w")) #保存到另外一个文件里
#修改
config.set('bitbucket.org', 'user', 'alex')
config.write(open('example.ini', "w")) #保存到另外一个文件里

3.正则表达式
2元字符:. ^ $ * + ? { } [ ] | ( ) \
import re
re.findall('w\w{2}l', 'hello world') #查找worl
print(ret)
# .是通配符
re.findall('w..l', 'hello world') #查找worl  一个点只能匹配一个字符
print(ret)
# ^
ret = re.findall('^h...o', 'hdewfdedfdsewhello') #只对开始匹配
print(ret)
# $
ret = re.findall('h...o$', 'hdewfdedfdsewhello') #只对结束匹配
print(ret)
# * 表示重复匹配
ret = re.findall('ba*', 'hdewfdedfdsewbaaaaaaa')
print(ret)
# + 表示[1, 正无穷]
ret = re.findall('ab+', 'kjldfah')
print(ret)
ret = re.findall('a+b', 'aaaaaabhghabfb')
print(ret)
# ? [0, 1]
ret = re.findall('a?b', 'aaaaaabhghabfb')  #a只要出现0或1次
print(ret)
# {} 
ret = re.findall('a{5}b', 'aaaaaabhghabfb')  #a连续出现5次
print(ret)
ret = re.findall('a{1, 3}b', 'aaaaaabhghabfb')  #a连续出现1到3次
print(ret)
{1,} 表示1到正无穷
结论:*等于{0,正无穷}  +等于{1,正无穷}  ?等于{0,1}
# [] 字符集
ret = re.findall('a[c,d]x', 'acx')
print(ret)
ret = re.findall('a-z', 'acx')
print(ret)
ret = re.findall('[w,*]', 'acx') #[]元字符:取消元字符的特殊功能,但 \ ^ - 例外
print(ret)
ret = re.findall('[^4,5]','serewr4dewer,d5u')
print(ret)
# \ 反斜杠后边跟元字符去除特殊功能, 反斜杠后边跟普通字符实现特殊功能
.   匹配除 "\n" 之外的任何单个字符。要匹配包括 '\n' 在内的任何字符,请使用象 '[.\n]' 的模式。
\d  匹配一个数字字符。等价于 [0-9]。
\D  匹配一个非数字字符。等价于 [^0-9]。
\s  匹配任何空白字符,包括空格、制表符、换页符等等。等价于 [ \f\n\r\t\v]。
\S  匹配任何非空白字符。等价于 [^ \f\n\r\t\v]。
\w  匹配包括下划线的任何单词字符。等价于'[A-Za-z0-9_]'。
\W  匹配任何非单词字符。等价于 '[^A-Za-z0-9_]'。
\b  匹配一个单词边界,例如单词和空格间的位置
print(re.findall('\d{11}', 'fadasdfsdfw2123212321234565434'))
print(re.findall('\wasd', 'fadasdfsdfw2123212321234565434'))
print(re.findall(r'I\b', 'hello, I am a LI$T'))
print(re.findall(r'\bI', 'hello, I am a LI$T'))

# search() 匹配出第一个满足条件的结果
ret=re.search('12', 'hello12wererw12')
print(ret.group())#获取内容
ret=re.search('1.2', 'hello12wererw1a2')
print(ret.group())#获取内容
ret = re.search('a\.', 'a.gj').group()
print(ret)
# +
print(re.search('(as)+','hello world asdfasdfe').group())
print(re.search('(as|5','hello world asdfas5dfe').group())

ret = re.search('(?P<id>\d{3})/(?P<name>\w{3})', 'weeeew34ttt123/ooo')
print(ret.group())
print(ret.group('id'))
print(ret.group('name'))
#
findall() 所有结果都返回到一个列表里
search() 返回一个对象(object),对象可以调用group()返回
match() 只在字符串开始匹配, 返回一个对象(object),对象可以调用group()返回
split()
ret=re.split('k','djksal')
print(ret)
ret = re.split('[j,s]','djksal')
print(ret)
ret=re.sub('a..x','s..b','fasedalexxdehf')  #把a**x替换成s..b
print(ret)
obj=re.compile('\.com')
ret=obj.findall('asdfew.comerewed')
print(ret)

4. os 模块
import os
os.sep:取代操作系统特定的路径分隔符
os.name:指示你正在使用的工作平台。比如对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'。
os.getcwd:得到当前工作目录,即当前python脚本工作的目录路径。
os.getenv()和os.putenv:分别用来读取和设置环境变量
os.listdir():返回指定目录下的所有文件和目录名
os.remove(file):删除一个文件
os.stat(file):获得文件属性
os.chmod(file):修改文件权限和时间戳
os.mkdir(name):创建目录
os.rmdir(name):删除目录
os.removedirs(r“c:\python”):删除多个目录
os.removedirs('abc\\alex\\alvin')
os.rename('test.text', 'test.txt') :修改文件名字为test.txt
os.system():运行shell命令
os.exit():终止当前进程
os.linesep:给出当前平台的行终止符。例如,Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'
os.path.split():返回一个路径的目录名和文件名
os.path.isfile()和os.path.isdir()分别检验给出的路径是一个目录还是文件
os.path.existe():检验给出的路径是否真的存在
os.listdir(dirname):列出dirname下的目录和文件
os.getcwd():获得当前工作目录
os.curdir:返回当前目录('.')
os.pardir:返回当前父目录('..')
os.chdir(dirname):改变工作目录到dirname
os.path.isdir(name):判断name是不是目录,不是目录就返回false
os.path.isfile(name):判断name这个文件是否存在,不存在返回false
os.path.exists(name):判断是否存在文件或目录name
os.path.getsize(name):或得文件大小,如果name是目录返回0L
os.path.abspath(name):获得绝对路径
os.path.isabs():判断是否为绝对路径
os.path.normpath(path):规范path字符串形式
os.path.split(name):分割文件名与目录(事实上,如果你完全使用目录,它也会将最后一个目录作为文件名而分离,同时它不会判断文件或目录是否存在)
os.path.splitext():分离文件名和扩展名
os.path.join(path,name):连接目录与文件名或目录
os.path.basename(path):返回文件名
os.path.dirname(path):返回文件路径
os.pathsep :系统分隔符
os.environ : 环境变量
os.path.dirname(__file__) :返回__file__的目录
os.path.getatime(path) :返回文件或目录最后存取时间
os.path.getmtime(path) :返回文件或目录最后修改时间
# sys 模块
import sys
sys.exit([arg]): 程序中间的退出,arg=0为正常退出。
sys.getdefaultencoding(): 获取系统当前编码,一般默认为ascii。
sys.setdefaultencoding(): 设置系统默认编码,执行dir(sys)时不会看到这个方法,在解释器中执行不通过,可以先执行reload(sys),在执行setdefaultencoding('utf8'),此时将系统默认编码设置为utf8。(见设置系统默认编码 )
sys.getfilesystemencoding(): 获取文件系统使用编码方式,Windows下返回'mbcs',mac下返回'utf-8'.
sys.path:包含输入模块的目录名列表。sys.path的第一个字符串是空的——这个空的字符串表示当前目录也是sys.path的一部分,这与PYTHONPATH环境变量是相同的。这意味着你可以直接输入位于当前目录的模块。否则,你得把你的模块放在sys.path所列的目录之一。
sys.platform: 获取当前系统平台。
sys.version  获取python版本
sys.maxint   最大的int值
sys.stdout.write('please:') 标准输出