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

 1#! /usr/bin/env python
 2# tree.py
 3# Written by Doug Dahms
 4# from www.361way.com
 5# Prints the tree structure for the path specified on the command line
 6from os import listdir, sep
 7from os.path import abspath, basename, isdir
 8from sys import argv
 9def tree(dir, padding, print_files=False):
10    print padding[:-1] + '+-' + basename(abspath(dir)) + '/'
11    padding = padding + ' '
12    files = []
13    if print_files:
14        files = listdir(dir)
15    else:
16        files = [x for x in listdir(dir) if isdir(dir + sep + x)]
17    count = 0
18    for file in files:
19        count += 1
20        print padding + '|'
21        path = dir + sep + file
22        if isdir(path):
23            if count == len(files):
24                tree(path, padding + ' ', print_files)
25            else:
26                tree(path, padding + '|', print_files)
27        else:
28            print padding + '+-' + file
29def usage():
30    return '''Usage: %s [-f] <PATH>
31Print tree structure of path specified.
32Options:
33-f      Print files as well as directories
34PATH    Path to process''' % basename(argv[0])
35def main():
36    if len(argv) == 1:
37        print usage()
38    elif len(argv) == 2:
39        # print just directories
40        path = argv[1]
41        if isdir(path):
42            tree(path, ' ')
43        else:
44            print 'ERROR: \'' + path + '\' is not a directory'
45    elif len(argv) == 3 and argv[1] == '-f':
46        # print directories and files
47        path = argv[2]
48        if isdir(path):
49            tree(path, ' ', True)
50        else:
51            print 'ERROR: \'' + path + '\' is not a directory'
52    else:
53        print usage()
54if __name__ == '__main__':
55    main()

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

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

 1linux-wdh1:/tmp/361way # tree /tmp/361way/
 2+-361way/
 3  |
 4  +-logs/
 5    |
 6    +-86/
 7linux-wdh1:/tmp/361way # tree -f /tmp/361way/
 8+-361way/
 9  |
10  +-test2.file
11  |
12  +-test.file
13  |
14  +-logs/
15  | |
16  | +-86/
17  | | |
18  | | +-messages
19  | | |
20  | | +-messages-20150426
21  | | |
22  | | +-messages-20150419
23  | | |
24  | | +-messages-20150510
25  | | |
26  | | +-messages-20150503
27  | |
28  | +-xkmessage.tar.gz
29  |
30  +-server.txt