当前位置: 移动技术网 > IT编程>脚本编程>Python > [Intern][2019.04.16] 由Python写成的自动解压脚本

[Intern][2019.04.16] 由Python写成的自动解压脚本

2019年04月17日  | 移动技术网IT编程  | 我要评论

王虎高芳,voiceao,中国食人村

很久很久以前(二十七天吧……大概)被要求写一个脚本来检索并解压磁盘上所有的以特定格式命名的tar文件,于是乎学习和摸鱼就一起开始了。

这次要写的脚本,针对的是这样的文件结构:

文件结构如上图所示

可以看到一个tar包里面套着两个tgz压缩包,我需要完成如下图所示的工作:

 

presson是个好东西

在python中,有两个可以调用系统指令的包,一个叫做sys,一个叫做os。比较棒的是它们在高级语言层面上是不区分操作系统的,同样一个变量 curdir 在 linux 下和在 win下都能拿到针对此操作系统可用的路径。而os.system() 或者 os.popen() 都可以完成将括号内带的参数变成系统使用的指令的工作,只要给出的指令是正确的。

在此次脚本编写中我学到一些新鲜玩意,在这里记录下来便于自己查阅。

 1 #! usr/bin/python
 2 import sys
 3 import re
 4 import os
 5 
 6 errormsg = "usage: python unzipautotriage.py [file location]. if file location was ommitted, script will work at current location."
 7 
 8 
 9 if len(sys.argv) == 1:
10     msg = raw_input("no arguments, script will work at current path(y/n):")
11     if msg != "y":
12         sys.exit(errormsg)
13     path = "."
14 elif len(sys.argv) >= 3:
15     if re.match(r'~?[a-za-z/\_.]*',sys.argv[1]) != none:
16         print "too many arguments, do you want to execute in", sys.argv[1], "(y/n):"
17         msg = raw_input()
18         if msg != "y":
19             sys.exit(errormsg)
20 else:
21     path = sys.argv[1]
22     print path
23 
24 command = "find " + path + " -mount -name 'auto_triage*.tar'"
25 filelist = os.popen(command).readlines()
26 status = dict.fromkeys(filelist,"not complete") # 创建一个字典用于保存每个文件的处理状态
27 print "found" , len(filelist) , "file"
28 if len(filelist) <= 0:
29     sys.exit("no such file, exiting....")
30 
31 rootpath = os.path.abspath(os.curdir)           # 保存一下运行起始目录,之后需要回来才能继续进行操作
32 
33 for path in filelist:
34     command = re.sub(r'auto.*.tar$','',path).replace("\n",'')
35     if os.path.abspath(os.curdir).split("/")[-1] != command.split("/")[-1]:
36         os.chdir(command)                       # 更换目录不能用os.system("cd xxxx")这种方法,过不去的……
37     print "unzipping", path
38     command = "tar -xvf " + re.sub(r'^\..*/auto','auto',path)
39     res = os.system(command)
40     if res == 0:
41         flag = 2
42         for item in ["spa","spb"]:
43             print "extracting ",item
44             command = "tar -xzvf " + path + item + ".service_dc.tgz -c " + path
45             command = re.sub(r'.tar\n','/',command)
46             res = os.system(command)
47             if res == 0:
48                 flag -= flag                    # python逻辑里面可没有什么自增自减!
49             else:
50                 status[path] =  str(flag) + " unzip subprogress failed"
51         if flag == 0:
52             status[path] = "completed"
53     else:
54         status[path] = "failed"
55     os.chdir(rootpath)
56 print "****************\nstatus report\n****************"
57 for key,value in status.items():
58     print '{key}status: {value}'.format(key = key, value = value)

具体踩到的一些坑,就记载到  采坑合集里面吧!

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网