python 内置模块

来源:互联网 发布:域名注册的网站名称 编辑:程序博客网 时间:2024/05/18 17:56

一:os模块,用于提供系统级别的操作

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

os.chdir("dirname")      改变当前脚本工作目录;相当于shell下cd

os.curdir               返回当前目录: ('.')

os.pardir               获取当前目录的父目录字符串名:('..')

os.makedirs('dirname1/dirname2')    可生成多层递归目录

os.removedirs('dirname1') 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推

os.mkdir('dirname')       生成单级目录;相当于shell中mkdir dirname

os.rmdir('dirname')       删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname

os.listdir('dirname')       列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印

os.remove()  删除一个文件

os.rename("oldname","newname")  重命名文件/目录

os.stat('path/filename')    获取文件/目录信息

os.sep                  输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"

os.linesep               输出当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"

os.pathsep              输出用于分割文件路径的字符串

os.name                  输出字符串指示当前使用平台。win->'nt'; Linux->'posix'

os.system("bashcommand")  运行shell命令,直接显示

os.environ               获取系统环境变量

os.path.abspath(path)      返回path规范化的绝对路径

os.path.split(path)         将path分割成目录和文件名二元组返回

os.path.dirname(path)      返回path的目录。其实就是os.path.split(path)的第一个元素

os.path.basename(path)    返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素

os.path.exists(path)        如果path存在,返回True;如果path不存在,返回False

os.path.isabs(path)        如果path是绝对路径,返回True

os.path.isfile(path)        如果path是一个存在的文件,返回True。否则返回False

os.path.isdir(path)         如果path是一个存在的目录,则返回True。否则返回False

os.path.join(path1[, path2[,...]])  将多个路径组合后返回,第一个绝对路径之前的参数将被忽略

os.path.getatime(path)     返回path所指向的文件或者目录的最后存取时间

os.path.getmtime(path)    返回path所指向的文件或者目录的最后修改时间

执行系统命令

os.system

os.spawn*

os.popen*         --废弃

popen2.*          --废弃

commands.*     --废弃,3.x中被移除

commands

import commandsresult = commands.getoutput('cmd')result = commands.getstatus('cmd')result = commands.getstatusoutput('cmd')

以上执行shell命令的相关的模块和函数的功能均在 subprocess 模块中实现,并提供了更丰富的功能。

call 

执行命令,返回状态码

1

2

ret = subprocess.call(["ls", "-l"], shell=False)

ret = subprocess.call("ls -l", shell=True)

shell = True ,允许 shell 命令是字符串形式

check_call

执行命令,如果执行状态码是 0 ,则返回0,否则抛异常

1

2

subprocess.check_call(["ls", "-l"])

subprocess.check_call("exit 1", shell=True)

check_output

执行命令,如果状态码是 0 ,则返回执行结果,否则抛异常

1

2

subprocess.check_output(["echo", "Hello World!"])

subprocess.check_output("exit 1", shell=True)

subprocess.Popen(...)

用于执行复杂的系统命令

参数:

args:shell命令,可以是字符串或者序列类型(如:list,元组)

bufsize:指定缓冲。0 无缓冲,1 行缓冲,其他缓冲区大小,负值系统缓冲

stdin, stdout, stderr:分别表示程序的标准输入、输出、错误句柄

preexec_fn:只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用

close_sfs:在windows平台下,如果close_fds被设置为True,则新创建的子进程将不会继承父进程的输入、输出、错误管道。
所以不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(stdin, stdout, stderr)。

shell:同上

cwd:用于设置子进程的当前目录

env:用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。

universal_newlines:不同系统的换行符不同,True -> 同意使用 \n

startupinfo与createionflags只在windows下有效
将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等

 

import subprocessret1 = subprocess.Popen(["mkdir","t1"])ret2 = subprocess.Popen("mkdir t2", shell=True)

终端输入的命令分为两种:

·        输入即可得到输出,如:ifconfig

·        输入进行某环境,依赖再输入,如:python

import subprocessobj = subprocess.Popen("mkdir t3", shell=True, cwd='/home/dev',)
obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)obj.stdin.write('print 1 \n ')obj.stdin.write('print 2 \n ')obj.stdin.write('print 3 \n ')obj.stdin.write('print 4 \n ')obj.stdin.close()cmd_out = obj.stdout.read()obj.stdout.close()cmd_error = obj.stderr.read()obj.stderr.close()print cmd_outprint cmd_error

 

import subprocessobj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)obj.stdin.write('print 1 \n ')obj.stdin.write('print 2 \n ')obj.stdin.write('print 3 \n ')obj.stdin.write('print 4 \n ')out_error_list = obj.communicate()print out_error_list

 

import subprocessobj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)out_error_list = obj.communicate('print "hello"')print out_error_list

其他:https://docs.python.org/3.5/library/os.html?highlight=os#module-os

 

二:sys模块:用于提供对解释器相关的操作

sys.argv           命令行参数List,第一个元素是程序本身路径

sys.exit(n)         退出程序,正常退出时exit(0)

sys.version         获取Python解释程序的版本信息

sys.maxint         最大的Int值

sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值

sys.platform       返回操作系统平台名称

sys.stdout.write('please:')

val = sys.stdin.readline()[:-1]

其他:https://docs.python.org/3.5/library/sys.html?highlight=sys#module-sys

 

三:hashlib模块:用于加密相关的操作,代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法

import hashlib# ######## md5 ########hash = hashlib.md5()hash.update(b'admin')print(hash.hexdigest())# ######## sha1 ########hash = hashlib.sha1()hash.update(b'admin')print(hash.hexdigest())# ######## sha256 ########hash = hashlib.sha256()hash.update(b'admin')print(hash.hexdigest())# ######## sha384 ########hash = hashlib.sha384()hash.update(b'admin')print(hash.hexdigest())# ######## sha512 ########hash = hashlib.sha512()hash.update(b'admin')print(hash.hexdigest())
 
### 输出结果
21232f297a57a5a743894a0e4a801fc3
d033e22ae348aeb5660fc2140aec35850c4da997
8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918
9ca694a90285c034432c9550421b7b9dbd5c0f4b6673f05f6dbce58052ba20e4248041956ee8c9a2ec9f10290cdc0782
c7ad44cbad762a5da0a452f9e854fdc1e0e7a52a38015f23f3eab1d80b931dd472634dfac71cd34ebc35d16ab7fb8a90c81f975113d6c7538dc69dd8de9077ec

 

其他:https://docs.python.org/3.5/library/hashlib.html

 

四:shutil模块:高级的 文件、文件夹、压缩包 处理模块

shutil.copyfileobj(fsrc,fdst[, length])
将文件内容拷贝到另一个文件中,可以部分内容

shutil.copymode(src,dst)
仅拷贝权限。内容、组、用户均不变

shutil.copystat(src,dst)
拷贝状态的信息,包括:mode bits, atime, mtime, flags

shutil.copy(src,dst)
拷贝文件和权限

shutil.copy2(src,dst)
拷贝文件和状态信息

shutil.ignore_patterns(*patterns)
shutil.copytree(src, dst, symlinks=False, ignore=None)

递归的去拷贝文件

例如:copytree(source,destination, ignore=ignore_patterns('*.pyc', 'tmp*'))

shutil.rmtree(path[,ignore_errors[, onerror]])
递归的去删除文件

shutil.move(src,dst)
递归的去移动文件

shutil.make_archive(base_name, format,...)

创建压缩包并返回文件路径,例如:zip、tar

·        base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
如:www                       =>保存至当前路径
如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/

·        format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”

·        root_dir: 要压缩的文件夹路径(默认当前目录)

·        owner: 用户,默认当前用户

·        group: 组,默认当前组

·        logger: 用于记录日志,通常是logging.Logger对象

 

#将 /Users/wupeiqi/Downloads/test 下的文件打包放置当前程序目录import shutilret = shutil.make_archive("wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test'#将 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目录import shutilret = shutil.make_archive("/Users/wupeiqi/wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')

shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的,详细:

zipfile 压缩解压

import zipfile# 压缩z = zipfile.ZipFile('laxi.zip', 'w')z.write('a.log')z.write('data.data')z.close()# 解压z = zipfile.ZipFile('laxi.zip', 'r')z.extractall()z.close()

tarfile 压缩解压

import tarfile# 压缩tar = tarfile.open('your.tar','w')tar.add('/Users/wupeiqi/PycharmProjects/bbs2.zip', arcname='bbs2.zip')tar.add('/Users/wupeiqi/PycharmProjects/cmdb.zip', arcname='cmdb.zip')tar.close()# 解压tar = tarfile.open('your.tar','r')tar.extractall()  # 可设置解压地址tar.close()

五:configparser模块:用于对特定的配置进行操作,

"""
[mysql]
db_host = 127.0.0.1
db_port = 3306
db_user = root
db_pass = password
[
个人信息]
name =
飞飞
age = 30
address = 重庆沙坪坝
tel = 13900000000
[add]
add1 = 添加字符串
add2 = 再添加字符串
[del]
del1 = 删除字符串
del2 = 删除字符串2
[dele]
dele1 = dele1的值
dele2 = dele2的值
"""              
#### 配置文件内容
import configparser

cf
= configparser.ConfigParser()

cf
= configparser.ConfigParser()
cf.read(
"ConfigParser.conf")

#返回所有的section
s = cf.sections()
print("section:",s)

print("*"*70)
o1
= cf.options("mysql")
print("options:mysql",o1)
o2
= cf.options("个人信息")
print("options:个人信息",o2)
o3
= cf.options("add")
print("options:add",o3)
o4
= cf.options("del")
print("options:del",o4)

print("*"*70)
v1
= cf.items("mysql")
print("items:mysql",v1)
v2
= cf.items("个人信息")
print("items:个人信息",v2)
v3
= cf.items("add")
print("items:add",v3)
v4
= cf.items("del")
print("items:del",v4)

print("*"*70)
db_host
= cf.get("mysql","db_host")
db_port
= cf.getint("mysql","db_port")
db_user
= cf.get("mysql","db_user")
db_pass
= cf.get("mysql","db_pass")

my_name
= cf.get("个人信息","name")
my_age
= cf.get("个人信息","age")
my_address
= cf.get("个人信息","address")
my_tel
= cf.get("个人信息","tel")

print("db_host:",db_host)
print("db_port:",db_port)
print("db_user:",db_user)
print("db_pass:",db_pass)
print("")
print("my_name:",my_name)
print("my_age:",my_age)
print("my_address:",my_address)
print("my_tel:",my_tel)

print("*"*60)
#添加[add]
#cf.add_section("addd")
#cf.write(open("ConfigParser.conf","w"))

if cf.has_section("addd"):
   
print("有了 [addd]了!")
else :
   
print("没有 [addd] !!现在开始写入:")
    cf.add_section(
"addd")
    cf.set(
"addd","addd1","addd1的值")
    cf.set(
"addd","addd2","addd2的值")
    cf.write(
open("ConfigParser.conf","w"))
   
print("[addd]写入完成")

#删除一个option
#cf.remove_opetion("del","del2")
#cf.write(open("ConfigParser.conf","w"))
if cf.has_option("del","del2"):
   
print("有del2,现在开始删除:")
    cf.remove_option(
"del","del2");
    cf.write(
open("ConfigParser.conf","w"))
   
print(" [del]下的 del2已经被删除!")
else :
    
print(" [del]下没有 del2了")

#删除section[dele]
#cf.remove_section("dele")
#cf.write(open("ConfigParser.conf","w"))
if cf.has_section("dele"):
   
print("有 [dele]了,开始删除:")
    cf.remove_section(
"dele")
    cf.write(
open("ConfigParser.conf","w"))
   
print("删除 [dele]成功")
else:
   
print("没有[dele],不需处理!")

#修改一个option
#
使用set()和新增加一样,这里不再写了
#cf.set("section","option","新值")

### 输出结果
[mysql]
db_host
= 127.0.0.1
db_port = 3306
db_user = root
db_pass
= password
[
个人信息]
name
= 飞飞
age
= 30
address = 重庆沙坪坝
tel
= 13900000000
[add]
add1
= 添加字符串
add2
= 再添加字符串
[
del]
del1
= 删除字符串
[addd]
addd1
= addd1的值
addd2
= addd2的值

此例借鉴:http://my.oschina.net/lenglingx/blog/205486

 

六:logging: 用于便捷记录日志且线程安全的模块

import logginglogging.basicConfig(filename='log.log',                    format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',                    datefmt='%Y-%m-%d %H:%M:%S %p',                    level=10) logging.debug('debug')logging.info('info')logging.warning('warning')logging.error('error')logging.critical('critical')logging.log(10,'log')

等级:只有大于当前日志等级的操作才会被记录。

CRITICAL = 50

FATAL = CRITICAL

ERROR = 40

WARNING = 30

WARN = WARNING

INFO = 20

DEBUG = 10

NOTSET = 0

 

七:time & datetime 模块:时间相关的操作,时间有三种表示方式:

import timeimport datetime print(time.clock()) #返回处理器时间,3.3开始已废弃print(time.process_time()) #返回处理器时间,3.3开始已废弃print(time.time()) #返回当前系统时间戳print(time.ctime()) #输出Tue Jan 26 18:23:48 2016 ,当前系统时间print(time.ctime(time.time()-86640)) #将时间戳转为字符串格式print(time.gmtime(time.time()-86640)) #将时间戳转换成struct_time格式print(time.localtime(time.time()-86640)) #将时间戳转换成struct_time格式,但返回 的本地时间print(time.mktime(time.localtime())) #与time.localtime()功能相反,将struct_time格式转回成时间戳格式#time.sleep(4) #sleepprint(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将struct_time格式转成指定的字符串格式print(time.strptime("2016-01-28","%Y-%m-%d") ) #将字符串格式转换成struct_time格式 #datetime module print(datetime.date.today()) #输出格式 2016-01-26print(datetime.date.fromtimestamp(time.time()-864400) ) #2016-01-16 将时间戳转成日期格式current_time = datetime.datetime.now() #print(current_time) #输出2016-01-26 19:04:30.335935print(current_time.timetuple()) #返回struct_time格式 #datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])print(current_time.replace(2014,9,12)) #输出2014-09-12 19:06:24.074900,返回当前时间,但指定的值将被替换 str_to_date = datetime.datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M") #将字符串转换成日期格式new_date = datetime.datetime.now() + datetime.timedelta(days=10) #比现在加10new_date = datetime.datetime.now() + datetime.timedelta(days=-10) #比现在减10new_date = datetime.datetime.now() + datetime.timedelta(hours=-10) #比现在减10小时new_date = datetime.datetime.now() + datetime.timedelta(seconds=120) #比现在+120sprint(new_date)

Directive

Meaning

Notes

%a

Locale’s abbreviated weekday name.

 

%A

Locale’s full weekday name.

 

%b

Locale’s abbreviated month name.

 

%B

Locale’s full month name.

 

%c

Locale’s appropriate date and time representation.

 

%d

Day of the month as a decimal number [01,31].

 

%H

Hour (24-hour clock) as a decimal number [00,23].

 

%I

Hour (12-hour clock) as a decimal number [01,12].

 

%j

Day of the year as a decimal number [001,366].

 

%m

Month as a decimal number [01,12].

 

%M

Minute as a decimal number [00,59].

 

%p

Locale’s equivalent of either AM or PM.

(1)

%S

Second as a decimal number [00,61].

(2)

%U

Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0.

(3)

%w

Weekday as a decimal number [0(Sunday),6].

 

%W

Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0.

(3)

%x

Locale’s appropriate date representation.

 

%X

Locale’s appropriate time representation.

 

%y

Year without century as a decimal number [00,99].

 

%Y

Year with century as a decimal number.

 

%z

Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59].

 

%Z

Time zone name (no characters if no time zone exists).

 

%%

A literal '%' character.

 

八:random模块:随机数

 

import randomprint random.random()print random.randint(1,2)print random.randrange(1,10)

生成随机的例子:

import randomcheckcode = ''for i in range(10):    current = random.randrange(0,4)    if current != i:        temp = chr(random.randint(65,90))    else:        temp = random.randint(0,9)    checkcode += str(temp)print(checkcode)

 

九:json 和 pickle模块

用于序列化的两个模块

json,用于字符串 和 python数据类型间进行转换

pickle,用于python特有的类型 和 python的数据类型间进行转换

Json模块提供了四个功能:dumps、dump、loads、load

pickle模块提供了四个功能:dumps、dump、loads、load

import pickledata = {'k1':123,'k2':'hello'}p_str = pickle.dumps(data)print(p_str)###import jsonj_str = json.dumps(data)print(j_str)

 

十:shelve模块:一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式

import shelved = shelve.open('test1.txt') #打开一个文件class Test(object):    def __init__(self,n):    self.n = nt = Test(123)t2 = Test(123334)name = ["alex","rain","test"]d["test"] = name #持久化列表d["t1"] = t       #持久化类d["t2"] = t2d.close()

 

 

0 0