为SuSE系统实现python tree

2015年7月10日 发表评论 阅读评论

centos/rhel下的tree命令非常好用,不过在SuSE下发现竟然没有该包,在SuSE的ISO镜像中也确认不存在该包 ,但是有的时候有想一目了解目录下的文件目录结构,所以就想到通过python实现一个。不过我这个比较懒,习惯先网上找下,能找到的话何必自己再去重复做无用功呢?还真找到了一个,代码如下:

#! /usr/bin/env python
# tree.py
# Written by Doug Dahms
# from www.361way.com
# Prints the tree structure for the path specified on the command line
from os import listdir, sep
from os.path import abspath, basename, isdir
from sys import argv
def tree(dir, padding, print_files=False):
    print padding[:-1] + '+-' + basename(abspath(dir)) + '/'
    padding = padding + ' '
    files = []
    if print_files:
        files = listdir(dir)
    else:
        files = [x for x in listdir(dir) if isdir(dir + sep + x)]
    count = 0
    for file in files:
        count += 1
        print padding + '|'
        path = dir + sep + file
        if isdir(path):
            if count == len(files):
                tree(path, padding + ' ', print_files)
            else:
                tree(path, padding + '|', print_files)
        else:
            print padding + '+-' + file
def usage():
    return '''Usage: %s [-f] <PATH>
Print tree structure of path specified.
Options:
-f      Print files as well as directories
PATH    Path to process''' % basename(argv[0])
def main():
    if len(argv) == 1:
        print usage()
    elif len(argv) == 2:
        # print just directories
        path = argv[1]
        if isdir(path):
            tree(path, ' ')
        else:
            print 'ERROR: \'' + path + '\' is not a directory'
    elif len(argv) == 3 and argv[1] == '-f':
        # print directories and files
        path = argv[2]
        if isdir(path):
            tree(path, ' ', True)
        else:
            print 'ERROR: \'' + path + '\' is not a directory'
    else:
        print usage()
if __name__ == '__main__':
    main()

将该文件命名为tree,并chmod +x tree 给予执行的权限,放到/usr/local/bin/目录下就可以直接调用了。

功能虽然没有centos上的tree强大,不过也该代码也实现了两个功能,默认只列出目录,加上-f参数,会将文件也列出。具体如下:

linux-wdh1:/tmp/361way # tree /tmp/361way/
+-361way/
  |
  +-logs/
    |
    +-86/
linux-wdh1:/tmp/361way # tree -f /tmp/361way/
+-361way/
  |
  +-test2.file
  |
  +-test.file
  |
  +-logs/
  | |
  | +-86/
  | | |
  | | +-messages
  | | |
  | | +-messages-20150426
  | | |
  | | +-messages-20150419
  | | |
  | | +-messages-20150510
  | | |
  | | +-messages-20150503
  | |
  | +-xkmessage.tar.gz
  |
  +-server.txt




本站的发展离不开您的资助,金额随意,欢迎来赏!

You can donate through PayPal.
My paypal id: itybku@139.com
Paypal page: https://www.paypal.me/361way

  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.