模块:用一段代码实现了某些功能的代码集合。
Python模块分为三种:
os模块:提供对操作系统进行调用的接口,以下是方法
os.getcwd() :获取当前工作目录,即当前python脚本工作的目录路径
示例:
1
2
3
4
|
>>> import os
>>> path = os.getcwd()
>>> print path
/Users/zenge
|
os.chdir("dirname") 改变当前脚本工作目录,相当于cd。
1
2
3
4
5
|
>>> print os.getcwd()
/Users/zenge/Downloads
>>> new_path = os.chdir( "/Users/zenge" )
>>> print os.getcwd()
/Users/zenge
|
os.curdir 返回当前目录:('.')
os.pardir 返回当前目录的父目录字符串名(‘..’)
示例:
os.makedirs('dirname1/dirname2') 可生成多层递归目录
1
2
|
>>> import os
>>> os.makedirs( 'aaa/bbb' )
|
os.removedirs('dirname1/dirname2') : 若目录为空,则删除,并递归到上一级目录,如果上一级目录也为空,则一并删除
>>> os.mkdir('aaaa'):生成单级目录,相当于linux命令mkdir
>>> os.listdir('aaaa'):列出目标目录下的所有文件和目录
1
2
3
|
[ 'b' , 'test' , 'a' , 'c' ]
root@localhost:~ /aaaa
a b c test
|
os.remove() 删除一个文件:
os.rename("oldname","newname"): 重命名一个目录/文件,如果新的文件名存在则报错
os.stat('path/filename'): 获取文件、目录信息
1
2
|
>>> os.stat( 'install.log' )
posix.stat_result(st_mode=33188, st_ino=262146, st_dev=64768L, st_nlink=1, st_uid=0, st_gid=0, st_size=9795, st_atime=1449083485, st_mtime=1449083572, st_ctime=1449083575)
|
os.sep:输出操作系统特定的路径分隔符,win下为“\\”,linux下为"/"
os.linesep:输出当前平台使用的行终止符,win下为“\t\n”,linux下为'\n'
os.pathsep 输出用于分割文件路径的字符串
os.name 输出字符串指示当前使用平台。win->'nt',linux->‘posix’
os.system("bash command"): 运行linux命令。
1
2
3
4
|
>>> os.system( 'ls' )
aa.py apache-ant-1.9.6-bin. tar .gz git-2.6.4 install .log jenkins.war
anaconda-ks.cfg epel-release-6-8.noarch.rpm git-2.6.4. tar .gz install .log.syslog
0
|
os.environ 获取系统环境变量
>>> os.environ
1
|
{ 'LESSOPEN' : '||/usr/bin/lesspipe.sh %s' , 'SSH_CLIENT' : '172.16.101.215 54940 22' , 'CVS_RSH' : 'ssh' , 'LOGNAME' : 'root' , 'USER' : 'root' , 'MAVEN_HOME' : '/usr/local/apache-maven' , 'PATH' : '/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/jdk1.8.0_66/bin:/usr/local/apache-maven/bin:/root/bin:/usr/local/git/bin:/root/bin' , 'LANG' : 'en_US.UTF-8' , 'TERM' : 'linux' , 'SHELL' : '/bin/bash' , 'SHLVL' : '1' , 'G_BROKEN_FILENAMES' : '1' , 'HISTSIZE' : '1000' , 'JAVA_HOME' : '/usr/local/jdk1.8.0_66' , 'HOME' : '/root' , 'CLASSPATH' : '.:/usr/local/jdk1.8.0_66/lib:/usr/local/jdk1.8.0_66/jre/lib' , 'JRE_HOME' : '/usr/local/jdk1.8.0_66/jre' , '_' : '/usr/bin/python' , 'SSH_CONNECTION' : '172.16.101.215 54940 10.10.10.201 22' , 'ANT_HOME' : '/usr/local/ant' , 'SSH_TTY' : '/dev/pts/1' , 'HOSTNAME' : 'localhost.localdomain' , 'HISTCONTROL' : 'ignoredups' , 'PWD' : '/root' , 'MAIL' : '/var/spool/mail/root' , 'LS_COLORS' : 'rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=01;05;37;41:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lz=01;31:*.xz=01;31:*.bz2=01;31:*.tbz=01;31:*.tbz2=01;31:*.bz=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.rar=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=01;36:*.au=01;36:*.flac=01;36:*.mid=01;36:*.midi=01;36:*.mka=01;36:*.mp3=01;36:*.mpc=01;36:*.ogg=01;36:*.ra=01;36:*.wav=01;36:*.axa=01;36:*.oga=01;36:*.spx=01;36:*.xspf=01;36:' }
|
os.path.abspath(path) 返回path规范化的绝对路径,文件不存在也会有输出结果
1
2
|
>>> os.path.abspath( 'aa.sh' )
'/root/aa.sh'
|
os.path.split(path) 返回path分割成目录和文件名二元组返回。
1
2
3
4
5
6
|
>>> os.path. split ( 'aa.sh' )
( '' , 'aa.sh' )
>>> os.path. split ( '/aa.sh' )
( '/' , 'aa.sh' )
>>> os.path. split ( '/etc/aa.sh' )
( '/etc' , 'aa.sh' )
|
os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)
1
2
3
4
|
>>> os.path. basename ( '/root/aa.py' )
'aa.py'
>>> os.path. basename ( '/root/aa.py/no' )
'no'
|
os.path.exists(path) 如果path存在,返回True,如果不存在,返回False
1
2
3
4
|
>>> os.path.exists( 'aa' )
False
>>> os.path.exists( '/root' )
True
|
os.path.isabs(path):如果path是绝对路径在返回True,否则返回False
1
2
3
4
|
>>> os.path.isabs( 'aa.py' )
False
>>> os.path.isabs( '/aa.py' )
True
|
os.path.isfile(path): 如果path是一个存在的文件,则返回True,否则返回False, 该方法会判断文件是否存在
1
2
3
4
|
>>> os.path.isfile( 'aa.py' )
True
>>> os.path.isfile( '/aa.py' )
False
|
os.path.isdir(path): 如果path是一个存在的目录,则返回True,否则返回False
1
2
3
4
|
>>> os.path.isdir( '/root' )
True
>>> os.path.isdir( '/abc' )
False
|
os.path.join(path1[,path2[, ...) :将多个路径组合后返回,第一个
os.path.getatime(path): 返回path所指向的文件或者目录的存取时间
1
2
|
>>> os.path.getatime( 'aa.py' )
1456380205.4800851
|
os.path.getmtime(path) 返回path所指向的文件或者目录的的最后修改时间
1
2
3
4
5
6
7
8
|
>>> os.path.getmtime( 'aa.py' )
1456374256.7410889
>>> os.path.getmtime( 'zabbix' )
Traceback (most recent call last):
File "<stdin>" , line 1, in <module>
File "/usr/lib64/python2.6/genericpath.py" , line 54, in getmtime
return os.stat(filename).st_mtime
OSError: [Errno 2] No such file or directory: 'zabbix'
|
os.popen('command').read() : 获取命令结果,不带命令执行状态
1
2
3
4
5
6
7
8
9
10
11
|
>>> a=os.popen( 'ls' ). read ()
>>> print a
aa.py
anaconda-ks.cfg
apache-ant-1.9.6-bin. tar .gz
epel-release-6-8.noarch.rpm
git-2.6.4
git-2.6.4. tar .gz
install .log
install .log.syslog
jenkins.war
|
sys模块
sys.argv :命令行参数list,第一个元素是程序本身
sys.exit(n): 退出程序,正常退出时exit(0)
sys.version:获取Python解释程序的版本信息
sys.maxint:最大的Int值
sys.path: 返回模块的的搜索路径,初始化时使用python
sys.platform:返回操作系统平台名称
sys.stout.write('please: ')
val=sys.stdin.readline()[:-1]
shutil模块:
是一种高层次的文件操作工具
类似于高级API,而且主要强大之处在于其对文件的复制与删除操作更是比较支持好

shutil.copyfile():copy文件内容,目标文件需要有写入的权限才行,否则把报IOError的错误
1
2
3
4
5
6
7
8
|
[root@localhost ~]
aaaaaaaa
[root@localhost ~]
>>> import shutil
>>> shutil.copyfile( 'a' , 'b' )
[root@localhost ~]
aaaaaaaa
|
如果没有权限写入b文件,则报错IOError
1
2
3
4
5
6
|
>>> shutil.copyfile( 'a' , 'yum.log' )
Traceback (most recent call last):
File "<stdin>" , line 1, in <module>
File "/usr/lib64/python2.6/shutil.py" , line 51, in copyfile
with open (dst, 'wb' ) as fdst:
IOError: [Errno 13] Permission denied: 'yum.log'
|
shutil.copymode():copy文件的权限,不赋值内容
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
[root@localhost ~]
total 0
-rwxr-xr-x. 1 root root 0 Jun 16 23:53 aaa
-rw-r--r--. 1 root root 0 Jun 16 23:53 bbb
[root@localhost ~]
aaa
aaa
aaa
>>> shutil.copymode( 'aaa' , 'bbb' )
>>>
查看bbb的权限,和aaa一样
[root@localhost ~]
total 4
-rwxr-xr-x. 1 root root 12 Jun 16 23:56 aaa
-rwxr-xr-x. 1 root root 0 Jun 16 23:53 bbb
[root@localhost ~]
[root@localhost ~]
bbb文件的内容为空,说明没有复制文件内容
|
shutil.copystate(): copy文件的权限,最后的访问时间、修改时间
先查看aaa、bbb文件的最后访问时间和修改时间:
ls -lu:查看文件的最后访问时间,即atime
ls -l:查看文件的最后修改时间
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
[root@localhost ~]
-rwxr-xr-x. 1 root root 4 Jun 17 00:04 aaa
-rwxr-xr-x. 1 root root 0 Jun 16 23:58 bbb
[root@localhost ~]
-rwxr-xr-x. 1 root root 4 Jun 17 00:04 aaa
-rwxr-xr-x. 1 root root 0 Jun 16 23:53 bbb
>>> shutil.copystat( 'aaa' , 'bbb' )
-rwxr-xr-x. 1 root root 4 Jun 17 00:04 aaa
-rwxr-xr-x. 1 root root 0 Jun 17 00:04 bbb
-[root@localhost ~]
-rwxr-xr-x. 1 root root 4 Jun 17 00:04 aaa
-rwxr-xr-x. 1 root root 0 Jun 17 00:04 bbb
|
shuti.copy() :将一个文件拷贝到另一个文件或者目录中,如果目标是文件,则只拷贝文件内容,不复制文件的修改时间、访问时间
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
复制文件到文件中
[root@localhost ~]
>>> shutil.copy( 'aaa' , 'ccc' )
[root@localhost ~]
[root@localhost ~]
total 8
-rwxr-xr-x. 1 root root 4 Jun 17 00:04 aaa
-rwxr-xr-x. 1 root root 0 Jun 17 00:04 bbb
-rwxr-xr-x. 1 root root 4 Jun 17 00:15 ccc
[root@localhost ~]
aaa
复制文件到目录中
>>> shutil.copy( 'aaa' , 'dir' )
[root@localhost ~]
total 4
-rwxr-xr-x. 1 root root 4 Jun 17 00:19 aaa
|
shutil.copy2() 在复制文件内容的基础上,在复制文件的访问时间,修改时间
1
2
3
4
5
6
7
8
9
|
[root@localhost ~]
-rwxr-xr-x. 1 root root 4 Jun 17 00:04 aaa
-rwxr-xr-x. 1 root root 4 Jun 17 00:15 ccc
>>> shutil.copy2( 'aaa' , 'ccc' )
[root@localhost ~]
-rwxr-xr-x. 1 root root 4 Jun 17 00:04 aaa
-rwxr-xr-x. 1 root root 4 Jun 17 00:04 ccc
|
shutil.copytree(olddir,newdir,True/False):把一个old 目录拷贝一份到new 目录(new目录必须不存在,否则报错),目录下的文件也会拷贝,如果第三个参数是True,则复制时保持目录下的符号链接,如果是False,则复制时生成文件来替代符号链接
1
2
3
4
5
|
[root@localhost ~]
dir :
aaa
new_dir/:
aaa
|
>>> shutil.copytree('dir','new2_dir',True)
1
2
3
4
5
|
[root@localhost ~]
dir :
aaa fstab_link
new2_dir/:
aaa fstab_link
|
>>> shutil.copytree('dir','new3_dir',False)
1
2
3
4
5
|
[root@localhost ~]
dir :
aaa fstab_link
new3_dir/:
aaa fstab_link
|
shutil.make_archive(base_name,format,...)
base_name:压缩包的文件名,也可以是压缩包的路径。如果只是包名,则表示为当前路径
format:压缩包种类,支持“zip”,“tar”,“bztar”,“gztar”
root_dir:要压缩的文件夹路径(默认当前目录)
owner:用户,默认为当前用户
group:组,默认当前组
logger:用于记录日志,通常是logging.logger对象
1
2
3
4
|
>>> shutil.make_archive( 'linux-packages.tar' , 'tar' , 'linux-packages' )
'/Users/zenge/Downloads/linux-packages.tar.tar'
~ /Downloads $ ls | grep tar
linux-packages. tar . tar
|
shutil对压缩包的处理是调用ZipFile和TarFile两个模块来进行的
time模块
时间相关的操作,时间有三种表示方式:
-
时间戳 1970年1月1日之后的秒,即:time.time()
-
格式化的字符串 2014-11-11 11:11, 即:time.strftime('%Y-%m-%d')
-
结构化时间 元组包含了:年、日、星期等... time.struct_time 即:time.localtime()
time.time()返回时间戳
print time.time()
1
2
|
python time_test.py
1471425695.52
|
time.gmtime()返回一个元组形式的结构化的字符串
print time.gmtime()
1
2
|
python time_test.py
time .struct_time(tm_year=2016, tm_mon=8, tm_mday=17, tm_hour=9, tm_min=37, tm_sec=38, tm_wday=2, tm_yday=230, tm_isdst=0)
|
time.strftime(%Y-%m-%d)返回指定格式的时间
print time.strftime(%Y-%m-%d %H:%M:%S)
1
2
|
python time_test.py
2016-08-17 17:36:07
|
以上三种时间是可以互相转换的
示例1:字符串格式的时间转换成结构化的时间
print time.strptime('2014-8-10','%Y-%m-%d')
python time_test.py
time.struct_time(tm_year=2014, tm_mon=8, tm_mday=10, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=222, tm_isdst=-1)
示例2:结构化的时间转换成时间戳
time.localtime() 返回结构化时间
print time.localtime()
python time_test.py
time.struct_time(tm_year=2016, tm_mon=8, tm_mday=17, tm_hour=17, tm_min=48, tm_sec=52, tm_wday=2, tm_yday=230, tm_isdst=0)
print time.mktime(time.localtime())
python time_test.py
1471427423.0
示例3:字符串时间转时间戳
字符串时间不能直接转换成时间戳,需要先转换成结构化时间,在转换成时间戳
print time.mktime(time.strptime('2016-5-01','%Y-%m-%d'))
1
2
|
python time_test.py
1462032000.0
|
执行系统命令的模块
os.system模块
os= os.system()
1
2
3
4
|
python time_test.py
class.py day4 func.py log11 pyhton_modules zabbix-api
coll.py email.py index.py log_new re_test.py 异常处理.py
day3 file_demo.py log logfile time_test.py
|
commands模块(Python3.x中被移除)
import commands
result = commands.getoutput('cmd')
result = commands.getstatus('cmd')
result = commands.getstatusoutput('cmd')
subprocess模块
call
执行命令,返回状态码
ret = subprocess.call(["ls", "-l"], shell=False)
ret = subprocess.call("ls -l", shell=True)
shell = True ,允许 shell 命令是字符串形式
check_call
执行命令,如果执行状态码是 0 ,则返回0,否则抛异常
subprocess.check_call([
"ls"
,
"-l"
])
subprocess.check_call(
"exit 1"
, shell
=
True
)
check_output
执行命令,如果状态码是 0 ,则返回执行结果,否则抛异常
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 subprocess
ret1 = subprocess.Popen(["mkdir","t1"])
ret2 = subprocess.Popen("mkdir t2", shell=True)
argpares模块
argparse是python用于解析命令行参数和选项的标准模块,用于代替已经过时的optparse模块。argparse模块的作用是用于解析命令行参数,例如python parseTest.py input.txt output.txt --user=name --port=8080。
二、使用步骤:
1:import argparse
2:parser = argparse.ArgumentParser()
3:parser.add_argument()
4:parser.parse_args()
解释:首先导入该模块;然后创建一个解析对象;然后向该对象中添加你要关注的命令行参数和选项,每一个add_argument方法对应一个你要关注的参数或选项;最后调用parse_args()方法进行解析
示例:
1
2
3
4
5
6
7
8
9
10
|
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument( "-H" , "--host" ,help= "host name" )
parser.add_argument( "-i" , "--ip" , help= "host ip" )
parser.add_argument( "-g" , "--group" , help= "group name" )
parser.add_argument( "-p" , "--proxy" , help= "proxy host name" )
parser.add_argument( "-t" , "--templates" , help= "template name" )
args = parser.parse_args()
return args
|