python模块整理1os模块

os 系统服务应用程序接口(API),系统管理员最应关注的模块之一。

重点os. path和一些系统相关函数。os.walk和os.path.walk区别

官方文档:
http://docs.python.org/library/os.html
http://docs.python.org/library/os.path.html


一、os模块
os.linesep 换行符,unix为'\n' dos/win32 为'\r\n'
不管你使用的是什么平台, 只要你导入了os模块, 这些变量自动会被设置为正确的值, 减少了你的麻烦.
os 模块属性 描述
linesep 用于在文件中分隔行的字符串
sep 用来分隔文件路径名的字符串
pathsep 用于分隔文件路径的字符串
curdir 当前工作目录的字符串名称
pardir (当前工作目录的)父目录字符串名称

(一)文件目录,权限相关
1、创建目录
os.mkdir(path [, mode=0777])
os.mkdir('/tmp/os_dir',0754)
2、删除目录
os.rmdir("/tmp/os_dir")
3、列出目录内容
os.listdir('/root')
结果为一个列表
4、更改文件目录
os.chdir('/tmp')
os.chroot('/tmp') #设置监牢目录
5、显示当前目录
os.getcwd()
'/tmp'
6、创建多层目录 类似系统makedir -p
os.makedirs('test/test1/test2')
7、删除多层目录【每层都是空的除了要删除目录外】
os.removedirs('/tmp/test/test1/test2')
8、创建一个文件
>>> f=open("/tmp/testfile", "w")
>>> f.write('test\n')
>>> f.close()
创建空文件呢?
>>> f=open("/tmp/testfile", "w")
>>> f.close()

os.mknod("test.txt")        创建空文件

9、删除文件
os.remove("/tmp/testfile")
10、查看文件状态
os.stat('/tmp/os_dir')
posix.stat_result(st_mode=16876, st_ino=17024L, st_dev=94L, st_nlink=2, st_uid=0, st_gid=0, st_size=512L, st_atime=1331646103, st_mtime=1331646103, st_ctime=1331646103)
依次是st_mode (权限模式), st_ino (inode number), st_dev (device), st_nlink (number of hard links), st_uid (所有者用户 ID), st_gid (所有者所在组 ID ), st_size (文件大小, 字节), st_atime (最近一次访问时间), st_mtime (最近修改时间), st_ctime (平台相关; Unix下的最近一次元数据/metadata修改时间, 或者 Windows 下的创建时间) - 以上项目也可作为属性访问
11、文件改名
文件夹改名
os.rename('/tmp/os_dir','/tmp/os_rename')
文件改名
os.rename('/tmp/testfile','/tmp/TSFILE')
12、文件权限修改
chmod(path, mode)
os.chmod('/tmp/os_rename',0777)
os.chmod('/tmp/TSFILE',0666)
os.lchmod(path, mode) 修改连接文件权限
13、文件属主修改
chown(path, uid, gid)
os.chown('/tmp/TSFILE',1003,1003)
os.chown('os_rename',0,1003)
14、umask
os.umask(022)
15、os.walk(topdirpath, topdown=True, onerror=None, followlinks=False)
os.walk()
函数声明:walk(top,topdown=True,onerror=None)
1>参数top表示需要遍历的目录树的路径
2>参数topdown的默认值是"True",表示首先返回目录树下的文件,然后在遍历目录树的子目录.Topdow
n的值为"False"时,则表示先遍历目录树的子目录,返回子目录下的文件,最后返回根目录下的文件
3>参数onerror的默认值是"None",表示忽略文件遍历时产生的错误.如果不为空,则提供一个自定义函
数提示错误信息后继续遍历或抛出异常中止遍历
4>该函数返回一个元组,该元组有3个元素,这3个元素分别表示每次遍历的路径名,目录列表和文件
列表
dirpath, dirnames, filenames
对于每个目录树中的目录根在顶部(包括顶部本身,但不包括.和..),产生一个3元组
组成的元组对象(dirpath,dirnames,文件名)
第一元素就是顶层目录,也就是walk方法的第一个参数
第二元素是顶层目录下子目录的列表
第三个元素为该目录的文件组成的列表
>>> for n in os.walk('/root'):
... print n[0],'wait'
... time.sleep(5)
... print n[1],'wait'
... time.sleep(5)
... print n[2],'wait'
dirroot.next() 第一次是查找的目录为顶层目录
第二次迭代就是顶层目录下其他字目录,然后依次就可以获取所有目录下面的文件
为了得到一个完整的路径(顶部开始)到一个文件或目录dirpath,做os.path.join(dirpath,filename)。
默认情况下,os.walk不遵循符号链接到子目录支持它们的系统。为了得到这个功能,设置可选参数'followlinks为true
将根目录和文件名连接在一起【包括目录和子目录都join】
for root,dir,file in os.walk('/root'):
[os.path.join(root,name) for name in file]
这个结果是每个文件和每个文件夹都是一个列表
for root,dir,file in os.walk('/root'):
for filename in file:
os.path.join(root,filename)
这个结果显示每一个文件的路径(包括隐藏文件)
....
【获取所有目录下文件最佳方式】
>>> path_collection=[]
>>> for root,dir,file in os.walk('/root'):
... for filename in file:
... fullpath=os.path.join(root,filename)
... path_collection.append(fullpath)
将目录全部文件的路径,保存到一个列表对象
说明:for出来root变量也会为子目录
..........
将根目录和子目录连接在一起
>>> for root, dirs, files in os.walk('/root'):
... for filename in dirs:
... os.path.join(root,filename)
这样打印出来好看
for root, dirs, files in os.walk('/root'):
[os.path.join(root,dirname) for dirname in dirs]
这样有很多空列表
【获取所有目录下子目录最佳方式】
>>> path_collection=[]
>>> for root,dir,file in os.walk('/root'):
... for dirname in dir:
... fullpath=os.path.join(root,dirname)
... path_collection.append(fullpath)
获取其他信息
>>> for root, dirs, files in os.walk('/root'):
... print root, "consumes",
... print sum([os.path.getsize(join(root, name)) for name in files]),
... print "bytes in", len(files), "non-directory files"
每一个目录都是root
(二)用户相关
os.getuid()
os.getgid()
os.getgroups()
os.getlogin() 登陆用户
(二)进程相关 已被subprocess取代
1、获取当前进程
os.getpid
2、执行操作系统命名
1)os.system(command)
这个方法直接返回命令的结果
command = "ls -l"
os.system(command)
os.system('ps -aux|grep python')
2)os.popen(command)
这个方法将命令返回值得保存到一个文件对象里,这个对象需要通过read()等方法读取内容。
Open a pipe to/from a command returning a file object. 这个文件对象保留在内存中。
p=os.popen('ssh 10.3.16.121 ps aux | grep mysql')
x=p.read()
print x
p.close()
print os.popen('ps aux | grep python').read()
如果不确定参数的安全性, 那么最好使用 exec 或 spawn
3、启动新的进程
>>> import os
>>> program = "python"
>>> arguments = ["hello.py"]
>>> os.execvp(program, (program,) + tuple(arguments))
hello again, and welcome to the show
使用的是execvp函数,它会从【标准路径搜索执行程序】,把第二个参数(元组)作为单独的参数传递给程
序,并使用当前的环境变量来运行程序. 其他七个同类型函数。
在 Unix 环境下, 你可以通过组合使用 exec , fork 以及 wait 函数来从当前程序调用另一个程序,
fork 函数复制当前进程, wait 函数会等待一个子进程执行结束.
3、os 模块调用其他程序 (Unix)
>>> def run(program, *args):
... pid = os.fork()
... if not pid:
... os.execvp(program, (program,) + args)
... return os.wait()[0]
>>> run("python", "hello.py")
hello again, and welcome to the show
1701
fork函数在子进程中返回0(这个进程首先从fork返回值),在父进程中返回一个非0的进程标识符(子进程的PID). 也就是说,
只有当我们处于父进程的时候 "not pid" 才为真.(即在子进程中pid为0,pid==0为真,在父进程中not pid(not 0),pid>0为真)
通过os模块中的fork方法,一个进程(Process)可以生成一个独立子进程。fork是一个程序拷贝(copyi
ng-program)的过程:当程序调用fork方法,操作系统生成一份该程序及其在内存中的进程的新的拷贝
,并以与原始程序并行的方式开始执行这份拷贝。原始程序称为父进程,新生成的拷贝叫做子进程。父
进程可以生成任意数目的子进程,子进程还可以生成它的子进程。这些子进程在操作系统的控制下相互独立的并行运行。子进程可以继续运行即便父进程已退出。
>>> def run(program, *args):
... pid = os.fork()
... if not pid:
... os.execvp(program, (program,) + args)
... return os.wait()
...
>>> run("python", "hello.py")
hello again, and welcome to the show
(1546, 0)
os.wait() 返回一个元组,这个两个数据代表什么? 第一元组已完成的子进程号pid,第二个元素为0表示子进程的退出状态
os.wait函数用于等待子进程结束(只适用于UNIX兼容系统)。该函数返回包含两个元素的元组,包括已完成的子进程号pid。以及子进程的退出状态,返回状态为0,表明子进程成功完成。返回状态为正整数表明子进程终止时出错.
如没有子进程,会引发OSError错误。os.wait
要求父进程等待它的任何一个子进程结束执行,然后唤醒父进程。要指示父进程等候一个指定的子进程终止,可在父进程中使用os.waitpid
函数(只适用于unix兼容系统).
它可等候一个指定进程结束,然后返回一个双元素元组,其中包括子进程的pid和子进程的退出状态。函数调用将pid
作为第一个参数传递。并将一个选项作为第二个选项,如果第一个参数大于0,则waitpid会等待该pid结束,如果第一个参数是-1
,则会等候所有子进程,也就和os.wait一样
参考http://developer.51cto.com/art/201003/185584.htm
fork和wait 函数在 Windows 上是不可用的, 但是你可以使用 spawn 函数, 不过, spawn
不会沿着路径搜索可执行文件, 你必须自己处理好这些
4、使用 os 模块调用其他程序 (Windows)
os.spawnv(os.P_WAIT, file, (file,) + args)
5、使用 spawn 或 fork/exec 调用其他程序
6、处理守护进程(Daemon Processes)
Unix系统中,你可以使用fork函数把当前进程转入后台(一个"守护者/daemon").一般来说,需要派生(fo
rk off)一个当前进程的副本, 然后终止原进程
import os
import time

pid = os.fork()
if pid:
os._exit(0) # kill original
print "daemon started"
time.sleep(10)
print "daemon terminated"
7、使用os模块终止当前进程
os._exit(0)
(三)执行操作系统命名
command = "ls -l"
os.system(command)
os.system('ps -aux|grep python')
(四)其他
1、获取环境变量
os.getenv('USER',default=None)
os.getenv('HOSTTYPE',default=None)
2、修改环境
putenv(key, value)
3、判断操作系统
os.name
if os.name in ("nt", "dos"):
exefile = ".exe"
else:
exefile = "
(五)os.path模块
os.path模块包含了各种处理长文件名(路径名)的函数.先导入os模块,然后就可以以os.path访问该模

1)简单的方法
拆分,目录名,文件名,连接
import os
filename = "my/little/pony"
print "using", os.name, "..."
print "split", "=>", os.path.split(filename)
print "splitext", "=>", os.path.splitext(filename)
print "dirname", "=>", os.path.dirname(filename)
print "basename", "=>", os.path.basename(filename)
print "join", "=>", os.path.join(os.path.dirname(filename),os.path.basename(filename))
结果
using posix ...
split => ('my/little', 'pony')
splitext => ('my/little/pony', '')
dirname => my/little
basename => pony
join => my/little/pony
注意这里的 split 只分割出最后一项(不带斜杠).
2、判断文件或文件夹是否存在
>>> os.path.exists(filename)
False
>>> os.path.exists('/root')
True
>>> os.path.exists('/root/wc.py')
True
3、判断是否是目录
>>> os.path.isdir('/root/wc.py')
False
>>> os.path.isdir('/root')
True
4、判断是否是文件
>>> os.path.isfile('/root')
False
>>> os.path.isfile('/root/wc.py')
True
5、判断是否是连接文件,是否是挂载文件
>>> os.path.islink('/root/wc.py')
>>> os.path.ismount('/root/wc.py')
6、判断两个目录是否有相同的文件
>>> os.path.samefile('/root/pathdir1','/root/pathdir2')
True
做了链接,判断就为真。
7、获取文件(文件夹)大小
>>> os.path.getsize('/root/pathdir1')
512L
8、获取文件时间戳
创建时间
>>> os.path.getctime('/root/pathdir1/person.py')
修改时间
>>> os.path.getmtime('/root/pathdir1/person.py')
访问时间
>>> os.path.getatime('/root/pathdir1/person.py')
9、walk(top, func, arg)
Directory tree walk with callback function.
os.path.walk()
函数声明:walk(top,func,arg)
1>参数top表示需要遍历的目录树的路径
2>参数func表示回调函数,对遍历路径进行处理.所谓回调函数,是作为某个函数的参数使用,当某个
时间触发时,程序将调用定义好的回调函数处理某个任务.回调函数必须提供3个参数:第1个参数为wa
lk()的参数arg,第2个参数表示目录列表,第3个参数表示文件列表
3>参数arg是传递给回调参数func的元组.回调函数的一个参数必须是arg,为回调函数提供处理参数.
参数arg可以为空
import os
def callback(arg, directory, files):
for file in files:
print os.path.join(directory, file), repr(arg)

os.path.walk("/root", callback, "secret message"
os.path.walk的第三个参数传给回调函数做第一参数,os.path.walk的第一个参数(目录)传递给回
调函数做第二个函数,回调函数的第三个函数就是目录下的file.
os.path.walk()与os.walk()产生的文件名列表并不相同.os.path.walk()产生目录树下的目录路径和\
文件路径,而os.walk()只产生文件路径.
# -*- coding: utf-8 -*-
import os
for root, dirs, files in os.walk('/root'):
open('/tmp/rootdir', 'a').write("%s %s %s" % (root,dirs,files))

几个自行进程的方法
os.execl(path, arg0, arg1, ...)
os.execle(path, arg0, arg1, ..., env)
os.execlp(file, arg0, arg1, ...)
os.execlpe(file, arg0, arg1, ..., env)
os.execv(path, args)
os.execve(path, args, env)
os.execvp(file, args)
os.execvpe(file, args, env)
这些函数将执行一个新程序, 替换当前进程; 他们没有返回.在Unix,新的执行体载入到当前的进程, 同时将和当前的调用者有相同的id. 将报告Errors 当抛出 OSError时.
>>> import psutil
> psutil.get_process_list()
> psutil.get_process_list()

原文地址:https://www.cnblogs.com/diege/p/2710619.html