python 根据菜单对tar进行相关操作

来源:互联网 发布:浅墨seo 编辑:程序博客网 时间:2024/06/14 07:05


#!/usr/bin/env pythonimport tarfile,systry:    tar=tarfile.open(sys.argv[1],'r:tar')#sys.argv[1]为执行命令时输入的第1个参数,sysargv[0]为当前执行脚本路径与脚本名称;以读的模式读取tar包,tar变量包含压缩包所有文件及其属性    selection=raw_input("Enter\n\1 to extract a file\n\2 to dispaly information on a file in the archive\n\3 to list all the files in the archive\n\n")        if selection=="1":        filename=raw_input("Enter the filename to extract: ")        tar.extract(filename)#解压某一个文件,extractall是解压所有文件,默认是解压到当前文件也可使用tar.extract(filename,path="/tmp")来指定路径    elif selection=="2":        filename=raw_input("Enter the filename to inspect: ")        for tarinfo in tar:            if tarinfo.name==filename:#对比到是想查的文件就将其打印出来,tar.getnames()获取压缩包里所有文件名称                print "\n\Filename:",tarinfo.name,"\n\    Size:",tarinfo.size,"bytes"    elif selection=="3":        print tar.list(verbose=True)#verbose=True时,相当于ls -l,为False时只例出文件名。tar.close()except:    print "There was a problem running the program"



执行结果

[root@localhost tmp]# ./tar.py /root/test.tarEnter1 to extract a file2 to dispaly information on a file in the archive3 to list all the files in the archive1Enter the filename to extract: test/444.log[root@localhost tmp]# ./tar.py /root/test.tarEnter1 to extract a file2 to dispaly information on a file in the archive3 to list all the files in the archive2Enter the filename to inspect: test/444.logFilename: test/444.log    Size: 7799 bytes[root@localhost tmp]# ./tar.py /root/test.tarEnter1 to extract a file2 to dispaly information on a file in the archive3 to list all the files in the archive3-rwxr-xr-x root/root          0 2015-01-09 05:19:35 test/-rw-r--r-- root/root       7799 2015-01-09 05:19:35 test/444.log-rw-r--r-- root/root     167678 2015-01-09 05:19:35 test/333.txt-rw-r--r-- root/root      10240 2015-01-09 05:19:35 test/2.pyNone


0 0