python3-day6(模块)

一、OS模块

  1、os.system('ls -l') #子shell运行,获取返回值,不是结果。

  2、os.popen('ls -l').read() #获取结果。

 

二、sys模块

  1、sys.argv

  2、sys.exit

  3、sys.path

三、shutil模块

  1、压缩归档

import shutil
ret = shutil.make_archive("/archive", 'gztar', root_dir='/var/log/www/access.log')

  2、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()

  3、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()

  4、shelve

import shelve
def CreateData():
    db=shelve.open('db.dat','c')
    db['int']=1
    db['float']=2.3
    db['string']='i like python.'
    db['key']='value'
    db.close()

def LoadData():
    db=shelve.open('db.dat','r')
    for item in db.items():
        print(item)
    db.close()
if __name__=="__main__":
    CreateData()
    LoadData()

  

 四、subprocess

import subprocess
1、call,run
subprocess.call('df -h',shell=True)
ret=subprocess.Popen('df -h',shell=True,stdout=subprocess.PIPE)
print(ret.stdout.read()

2、交互
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 ')

out_error_list = obj.communicate()
print out_error_list

  

posted @ 2016-04-18 08:14  willianflasky  阅读(157)  评论(0编辑  收藏  举报