374
|
1 #!/usr/bin/env python
|
|
2 # -*- coding: utf-8 -*-
|
|
3
|
|
4 """
|
|
5 tree in python
|
|
6 """
|
|
7
|
|
8 import optparse
|
|
9 import os
|
|
10 import sys
|
|
11
|
|
12 here = os.path.dirname(os.path.realpath(__file__))
|
|
13
|
|
14 def depth(directory):
|
|
15 directory = os.path.abspath(directory)
|
|
16 level = 0
|
|
17 while True:
|
|
18 directory, remainder = os.path.split(directory)
|
|
19 level += 1
|
|
20 if not remainder:
|
|
21 break
|
|
22 return level
|
|
23
|
|
24 def tree(directory):
|
|
25 retval = []
|
|
26 level = depth(directory)
|
|
27 directories = {}
|
|
28 for dirpath, dirnames, filenames in os.walk(directory, topdown=True):
|
|
29 indent = depth(dirpath) - level
|
|
30 dirnames[:] = sorted(dirnames, key=lambda x: x.lower())
|
|
31 directories[dirpath] = dirnames
|
|
32 retval.append('%s%s%s' % ('│' * (indent-1),
|
|
33 '├' if indent else '',
|
|
34 os.path.basename(dirpath)))
|
|
35 retval.extend(['%s%s%s' % ('│' * (indent),
|
|
36 '├' if index < len(filenames) -1 else '└',
|
|
37 name)
|
|
38 for index, name in
|
|
39 enumerate(sorted(filenames, key=lambda x: x.lower()))
|
|
40 ])
|
|
41 return '\n'.join(retval)
|
|
42
|
|
43 def main(args=sys.argv[1:]):
|
|
44
|
|
45 usage = '%prog [options]'
|
|
46 parser = optparse.OptionParser(usage=usage, description=__doc__)
|
|
47 options, args = parser.parse_args(args)
|
|
48 if not args:
|
|
49 args = ['.']
|
|
50
|
|
51 not_directory = [arg for arg in args
|
|
52 if not os.path.isdir(arg)]
|
|
53 if not_directory:
|
|
54 parser.error("Not a directory: %s" % (', '.join(not_directory)))
|
|
55
|
|
56 for arg in args:
|
|
57 print (tree(arg))
|
|
58
|
|
59 if __name__ == '__main__':
|
|
60 main()
|