Python标准库04

本文主要介绍Python标准库。

1.subprocess模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
>>> import subprocess
>>> retcode = subprocess.call(["ls", "-l"])
#和shell中命令ls -a显示结果一样
>>> print retcode
>>> retcode = subprocess.call("ls -l",shell=True)
>>> child = subprocess.Popen(['ping','-c','4','blog.linuxeye.com'])
>>> print 'parent process'

------------------------------华丽的分割线-----------------------------

>>> import subprocess
>>> child = subprocess.Popen('ping -c4 blog.linuxeye.com',shell=True)
>>> child.wait()
>>> print 'parent process'

------------------------------华丽的分割线-----------------------------

>>> import subprocess
>>> child1 = subprocess.Popen(["ls","-l"], stdout=subprocess.PIPE)
>>> print child1.stdout.read(),
#或者child1.communicate()

------------------------------华丽的分割线-----------------------------

>>> import subprocess
>>> child1 = subprocess.Popen(["cat","/etc/passwd"], stdout=subprocess.PIPE)
>>> child2 = subprocess.Popen(["grep","0:0"],stdin=child1.stdout, stdout=subprocess.PIPE)
>>> out = child2.communicate()

2.pyinotify模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#!/usr/bin/python
# coding:utf-8

import os
from pyinotify import WatchManager, Notifier,ProcessEvent,IN_DELETE, IN_CREATE,IN_MODIFY

class EventHandler(ProcessEvent):
"""事件处理"""
def process_IN_CREATE(self, event):
print "Create file: %s " % os.path.join(event.path,event.name)

def process_IN_DELETE(self, event):
print "Delete file: %s " % os.path.join(event.path,event.name)

def process_IN_MODIFY(self, event):
print "Modify file: %s " % os.path.join(event.path,event.name)

def FSMonitor(path='.'):
wm = WatchManager()
mask = IN_DELETE | IN_CREATE |IN_MODIFY
notifier = Notifier(wm, EventHandler())
wm.add_watch(path, mask,auto_add=True,rec=True)
print 'now starting monitor %s'%(path)
while True:
try:
notifier.process_events()
if notifier.check_events():
notifier.read_events()
except KeyboardInterrupt:
notifier.stop()
break

if __name__ == "__main__":
FSMonitor('/root/softpython/apk_url')

3.pwd和grp模块

pwd模块:
pwd.getpwuid(uid):
返回对应uid的用户信息
pwd.getpwnam(name):
返回对应name的用户信息
pwd.getpwall():
返回所有用户信息
grp.getgrgid(gid):
返回对应gid的组信息
grp.getgrname(name):
返回对应group name的组信息
grp.getgrall():
返回所有组信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import pwd

def get_user():
all_user = {}
for user in pwd.getpwall():
all_user[user[0]] = all_user[user[2]] = user
return all_user

def userinfo(uid):
return get_user()[uid]

print userinfo(0)
pwd.struct_passwd(pw_name='root', pw_passwd='x', pw_uid=0, pw_gid=0, pw_gecos='root', pw_dir='/root', pw_shell='/bin/bash')
print userinfo('root')
pwd.struct_passwd(pw_name='root', pw_passwd='x', pw_uid=0, pw_gid=0, pw_gecos='root', pw_dir='/root', pw_shell='/bin/bash')

4.pickle模块

  • 使用pickle模块将数据对象保存到文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    #!/usr/bin/env python
    # coding:utf-8
    import pickle

    data1 = {'a': [1, 2.0, 3, 4+6j],
    'b': ('string', u'Unicode string'),
    'c': None}

    selfref_list = [1, 2, 3]
    selfref_list.append(selfref_list)

    output = open('data.pkl', 'wb')

    #pickle.dump(obj, file, [,protocol])
    #注解:将对象obj保存到文件file中去。
    #protocol为序列化使用的协议版本
    #0:ASCII协议
    #1:老式的二进制协议
    #2:2.3版本引入的新二进制协议,较以前的更高效。
    pickle.dump(data1, output)
    pickle.dump(selfref_list, output, 2)
    output.close()
  • 使用pickle模块从文件中重构python对象

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    #!/usr/bin/env python
    # coding:utf-8

    import pprint, pickle

    pkl_file = open('data.pkl', 'rb')
    data1 = pickle.load(pkl_file)
    pprint.pprint(data1)
    data2 = pickle.load(pkl_file)
    pprint.pprint(data2)
    pkl_file.close()

5.yaml模块

  • 写入yaml文件:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    #!/usr/bin/env python
    # coding:utf-8

    import yaml
    yaml_file = open('test.yaml','w')
    data = {'user_info':{'name':A, 'age':17}}
    yaml.dump(data,yaml_file)
    #yaml_file.truncate //清空yaml文件
    yaml_file.close()
  • 读取yaml文件:

    1
    2
    3
    4
    5
    6
    7
    #!/usr/bin/env python
    # coding:utf-8

    import yaml
    yaml_file = open('test.yaml','r')
    yaml.load(yaml_file)
    yaml_file.close()

6.optparser模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/usr/bin/env python
# coding:utf-8

from optparse import OptionParser
usage = "myprog[ -f <filename>][-s <xyz>] arg1[,arg2..]"
optParser = OptionParser(usage)
optParser.add_option("-f","--file",action = "store",type="string",dest = "fileName")
ooptParser.add_option("-v","--vison", action="store_false", dest="verbose",default='None',
help="make lots of noise [default]")
fakeArgs = ['-f','file.txt','-v','good luck to you', 'arg2', 'arge']
options, args = optParser.parse_args(fakeArgs)
print options.fileName
print options.verbose
print options
print args
print optParser.print_help()
---------------- The End ----------------