algorithm-in-python/utils/tree.py

64 lines
1.8 KiB
Python
Raw Normal View History

2018-12-11 15:57:58 +08:00
''' mbinary
#########################################################################
# File : tree.py
# Author: mbinary
# Mail: zhuheqin1@gmail.com
2019-01-31 12:09:46 +08:00
# Blog: https://mbinary.xyz
2018-12-11 15:57:58 +08:00
# Github: https://github.com/mbinary
# Created Time: 2018-12-11 15:56
# Description:
#########################################################################
'''
# coding: utf-8
import os
from argparse import ArgumentParser
2020-04-15 12:28:20 +08:00
# 命令行输入参数处理
2018-12-11 15:57:58 +08:00
parser = ArgumentParser()
2020-04-15 12:28:20 +08:00
parser.add_argument('-p', '--path', default='.', help='path to walk')
parser.add_argument('-f', '--fileinclude', action='store_true',
help='if has, list files and dirs, else only dirs')
parser.add_argument('-d', '--depth', type=int, default=2)
# 获取参数
2018-12-11 15:57:58 +08:00
args = parser.parse_args()
FILE = args.fileinclude
PATH = args.path
DEPTH = args.depth
2020-04-15 12:28:20 +08:00
2018-12-11 15:57:58 +08:00
def mklink(path):
2020-04-15 12:28:20 +08:00
return '* [{name}]({path})'.format(name=os.path.basename(path), path=path)
2018-12-11 15:57:58 +08:00
def clean(paths):
ret = []
for path in paths:
name = os.path.basename(path)
2020-04-15 12:28:20 +08:00
if not (name.startswith('.') or name.startswith('__')):
2018-12-11 15:57:58 +08:00
ret.append(path)
return ret
2020-04-15 12:28:20 +08:00
def tree(path='.', depth=2, showfile=False):
2018-12-11 15:57:58 +08:00
li = []
2020-04-15 12:28:20 +08:00
if os.path.isdir(path):
li = os.listdir(path)
else:
li = [path]
items = [os.path.join(path, i) for i in li if not i.startswith('.')]
2018-12-11 15:57:58 +08:00
items = clean(items)
items = sorted(items)
2020-04-15 12:28:20 +08:00
if not showfile:
items = [i for i in items if os.path.isdir(i)]
if depth == 1:
2018-12-11 15:57:58 +08:00
return [mklink(path)] + [' '*4 + mklink(i) for i in items]
else:
2020-04-15 12:28:20 +08:00
uls = [tree(i, depth-1, showfile) for i in items]
2018-12-11 15:57:58 +08:00
ret = [' '*4 + li for ul in uls for li in ul]
2020-04-15 12:28:20 +08:00
return [mklink(path)] + ret
2018-12-11 15:57:58 +08:00
2020-04-15 12:28:20 +08:00
if __name__ == '__main__':
print('\n'.join(tree(PATH, DEPTH, FILE)))