The implementation code is as follows:
Description: Now the code has implemented the DU Command's-s statistical function, statistics and the System du command slightly different, such as with the ls-ld/root result of 4096, and Du calculated is 1040, with the current Python is also calculated 4096.
#!/usr/bin/python#*-*coding:utf8*-*import sysimport osfrom optparse import optionparser# use option Help information can be used in Chinese reload (SYS) sys.setdefaultencoding ("Utf-8") #定义选项和帮助信息usage = sys.argv[0] + " [options]... [objects] ..." parser = optionparser (usage) parser.add_option ("-S", dest= "Sum", action= "Store_true", default=False, help= "Count the sum of the size of the specified object") parser.add_option ("-A", dest= "AutoDisplay", action= "Store_true", default=False, help= " Automatic display of k,KB,MB,GB units according to size ") Options, args = parser.parse_args () #判断文件或目录是否存在def Nofile (i): if not os.path.exists (i): sys.stderr.write (i + "\tis not exists\n") exit (1) #定义显示样式def autodisplay (num): float (num) IF&NBSP;NUM&NBSP;<&NBSP;1024:&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;RETURN&NBSP;STR (num) + "B" elif num < 1024*1024: &NBSP;&NBSP;RETURN&NBSP;STR ("%.1f" % (num/1024) + "K" elif num < 1024*1024*1024: return str ("%.1f" % (num/1024/1024)) + "M" else: return str ("%.2f" % (num /1024/1024/1024)) + "G" Sum = 0for i in args: nofile ( i) if os.path.isfile (i): size = os.path.getsize (i) sum += size print ("%s\t%s" % (Autodisplay (sum), i)) if os.path.isdir (i): dir = os.walk (i) for x, y, z in dir: size = os.path.getsize (x) #对目录本身进行大小统计, and du statistical results a little bit different. sum += size if options.sum: pass else: if options.autoDisplay: print ("%s\t%s" % (autoDisplay (size ), x) else: print ("%d\t%s" % ( size, x)) for f in z: size = os.path.getsize (Os.path.join (x, f)) #对目录里面文件进行大小统计 sum += size if options.sum: pass else : if options.autoDisplay: print ("%s\t%s" % (autoDisplay (size), Os.path.join (x, f)) else: print ("%d\t%s" % (Size, os.path.join (x, f)) "" If you add the-S option, enter the total size "" " if options.sum: print ("%s\t%s" % (AutoDisplay (SUM) , i))
The results of the program execution are as follows:
650) this.width=650; "Src=" https://s3.51cto.com/wyfs02/M00/98/93/wKioL1k-StDQOjg2AADhi41RDDA826.png-wh_500x0-wm_ 3-wmp_4-s_3426233345.png "title=" appptp7[{a~n8c9$u67s[' A.png "alt=" wkiol1k-stdqojg2aadhi41rdda826.png-wh_50 "/ >
650) this.width=650; "Src=" https://s3.51cto.com/wyfs02/M02/98/96/wKioL1k-ZFGALrXRAADEOS5aNXk565.png-wh_500x0-wm_ 3-wmp_4-s_3803990715.png "title=" D6@ns[9cap1ykq%3ndm1zc0.png "alt=" wkiol1k-zfgalrxraadeos5anxk565.png-wh_50 "/ >
This article is from the "Blue _ Storm" blog, make sure to keep this source http://270142877.blog.51cto.com/12869137/1934616
Python implements simple du command in Linux