您的位置:首页 > 编程语言 > Python开发

python学习4 常用内置模块

2016-03-15 21:25 746 查看

logging

os

路径处理

// 获取当前路径
os.path.abspath(__file__)

//获取当前文件夹路径
os.path.dirname(os.path.abspath(__file__))
os.path.abspath('.')

//路径拼接处理
os.path.join(path1, path2)


创建链接

//创建硬/文件链接
os.link('oops.txt', 'yikes.txt')
//创建符号链接
os.symlink('oops.txt', 'jeepers.txt')
//检查文件还是符号链接
os.path.islink('jeepers.txt') //False
//获取符号链接路径
os.path.realpath('jeepers.txt')


获取进程信息

import os
os.getegid()
os.getcwd()

shutil

复制内容

import shutil
shutil.copy('oops.txt', 'ohno.txt')

glob

列出匹配文件

import glob
print(glob.glob('*'))

sys

获取执行参数

sys.argv

subprocess

执行命令

subprocess.Popen(command)

time

使用
sleep


try:
while True:
print('start')
time.sleep(2)
print('end')
except KeyboardInterrupt:
print('stop')


事件处理

//获取当前秒
time.time()

datetime

通过时间戳获取日期

from datetime import datetime
dt = datetime.fromtimestamp(t)
dt.year  ;dt.month  ;dt.day

inspect 检查运行模块的一些基本信息

判断generator函数

from inspect import isgeneratorfunction
isgeneratorfunction(fab)


获取参数

inspect.signature(fn)

types

判断generator函数和generator实例

import types
isinstance(fab, types.GeneratorType)
isinstance(fab(5), types.GeneratorType)

pickle

把对象序列化成bytes

//把对象序列化成bytes
byte_data = pickle.dumps({"name": "jinks"})

//反操作
pick.loads(byte_data)

json

例子

Python对象和JSON的转化

json_str = json.dumps(data)
data = json.loads(json_str)

functools 高阶函数相关的模块

消除装饰器带来__name__改变的副作用

def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper

@decorator
def add(x, y):
return x + y

urllib, urllib2 处理url相关操作的库

分析http查询字符串

urllib.parse.parse_qs 返回字典
urllib.parse.parse_qsl 返回列表

collections 内建的集合模块

deque实现插入删除操作的双向列表

from collections import deque

q = deque(['a', 'b', 'c'])
q.append('x')
q.appendleft('y')

heapq 实现堆排序

查找最值

import heapq
nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
print(heapq.nlargest(3, nums)) # Prints [42, 37, 23]
print(heapq.nsmallest(3, nums)) # Prints [-4, 1, 2]

//
portfolio = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'AAPL', 'shares': 50, 'price': 543.22},
{'name': 'FB', 'shares': 200, 'price': 21.09},
{'name': 'HPQ', 'shares': 35, 'price': 31.75},
{'name': 'YHOO', 'shares': 45, 'price': 16.35},
{'name': 'ACME', 'shares': 75, 'price': 115.65}
]
cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])
expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price'])

re

split 字符串分割

from re import split
line = 'asdf fjdk; afed, fjek,asdf, foo'
rs = split(r'[;,\s]\s*', line)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: