Python argparse模块实现模拟 linux 的ls命令
python 模拟linux的 ls 命令
sample: python custom_ls.py -alh c:/
选项:
-a ,--all 显示所有文件,包括'.'开头的隐藏文件
-l 列表显示每个文件详细信息
-h 以人类可读的方式显示,文件大小会被换算成 K、M、G、T 或 P 的单位
path
只能接受一个path路径,需要改进。
from pathlib import Path
import argparse
import datetime
import stat
import os def convert_mode(mode: int):
modelist = ['r', 'w', 'x', 'r', 'w', 'x', 'r', 'w', 'x']
m = mode & 0o777
modestr = bin(m)[-9:]
ret = ""
for i, v in enumerate(modestr):
if v == '1':
ret += modelist[i]
else:
ret += '-'
return ret def convert_type(file: Path):
ret = ""
if file.is_symlink():
ret = 'l'
elif file.is_fifo():
ret = 'p'
elif file.is_socket():
ret = 's'
elif file.is_block_device():
ret = 'b'
elif file.is_char_device():
ret = 'c'
elif file.is_dir():
ret = 'd'
elif file.is_file():
ret = '-'
else:
ret = '?'
return ret def list_dir(path: str = '.', all=False, detail=False, human=False):
units = ['', 'K', 'M', 'G', 'T', 'P'] def _convert_human(size: int):
depth = 0
while size >= 1024:
size = size // 1024
depth += 1
return "{}{}".format(size, units[depth]) def _show_dir(path: str = '.', all=False, detail=False, human=False):
p = Path(path)
for file in p.iterdir():
if not all and str(file.name).startswith('.'):
continue if detail:
st = file.stat() h = st.st_size
if human:
h = _convert_human(st.st_size) owner, group = st.st_uid, st.st_gid
if os.name == "posix":
owner, group = file.owner(), file.group() yield str((stat.filemode(st.st_mode), st.st_nlink, owner, group, str(h),
datetime.datetime.fromtimestamp(st.st_atime).strftime('%Y-%m-%d %H:%M:%S'),
file.name)).strip(
'()')
else:
yield str((file.name,)).strip('()') yield from sorted(_show_dir(args.path, args.all, args.l, args.h), key=lambda x: x[-1]) parser = argparse.ArgumentParser(prog='ls', add_help=False, description='list directory contents. --20171031')
parser.add_argument('path', nargs='?', default='.', help='give a path (files or direction)')
parser.add_argument('-l', action='store_true', help='List Display details')
parser.add_argument('-h', action='store_true', help='Human readable way to show "kmgtp" size')
parser.add_argument('-a', '--all', action='store_true', help='Show hidden files at the same time') if __name__ == '__main__':
args = parser.parse_args(('.', '-ahl'))
parser.print_help()
print('args=', args) for st in list_dir(args.path, args.all, args.l, args.h):
print(st)
Python argparse模块实现模拟 linux 的ls命令的更多相关文章
- Python argparse 模块
Python argparse 模块 test.py: import argparse argparser = argparse.ArgumentParser(add_help=False) argp ...
- python - argparse 模块学习
python - argparse 模块学习 设置一个解析器 使用argparse的第一步就是创建一个解析器对象,并告诉它将会有些什么参数.那么当你的程序运行时,该解析器就可以用于处理命令行参数. 解 ...
- Linux下 ls 命令的高级用法8例
Linux下 ls 命令的高级用法8例 在Linux下,ls这个命令大家肯定太熟悉了,良许相信只要是Linux工程师,每天都会离不开这个命令,而且一天会使用个几百次.但是,除了 ls -l 以外,你还 ...
- python datetime模块strptime/strptime format常见格式命令_施罗德_新浪博客
python datetime模块strptime/strptime format常见格式命令_施罗德_新浪博客 python datetime模块strptime/strptime form ...
- Linux下ls命令显示符号链接权限为777的探索
Linux下ls命令显示符号链接权限为777的探索 --深入ls.链接.文件系统与权限 一.摘要 ls是Linux和Unix下最常使用的命令之一,主要用来列举目录下的文件信息,-l参数允许查看当前目录 ...
- Linux的ls命令在Windows中的应用
Linux的ls命令在Windows中的应用 注:ls是Linux中的命令.其作用是列出当前目录下的文件与文件夹.效果等同于Wndows中的dir指令. 如下图 下面是详细步骤 步骤一.在桌面新建一个 ...
- python argparse模块解析命令行选项简单使用
argparse模块的解析命令行选项简单使用 util.py #!/usr/bin/env python # coding=utf-8 import argparse parser = argpars ...
- Python Argparse模块
argparse模块 在Python中,argparse模块是标准库中用来解析命令行参数的模块,用来替代已经过时的optparse模块.argparse模块能够根据程序中的定义从sys.argv中解析 ...
- Changing the Color of Linux ls Command 改变Linux的ls命令显示的颜色
Linux command ls basically use the file /etc/DIR_COLORS or /etc/DIR_COLORS.xterm to define the color ...
随机推荐
- win10 uwp 车表盘 径向规
车表盘就是有刻度的圆盘加上针,这个控件可以直观让用户知道当前的速度或其他 看名字不知道是什么,我就放一张图 使用很简单,在Nuget,Radial Gauge 要使用大神做的,简单,在使用我们需要在N ...
- Volley图片加载并加入缓存处理(转自http://blog.csdn.net/viewhandkownhealth/article/details/50957024)
直接上代码 两种方式 ImageView 和NetworkImageView 如有问题或者好的建议.意见 欢迎大家加入技术群(群号: 387648673 ) 先自定义全局Application 获取 ...
- ELK系列~Nxlog日志收集加转发(解决log4日志换行导致json转换失败问题)
本文章将会继承上一篇文章,主要讲通过工具来进行日志的收集与发送,<ELK系列~NLog.Targets.Fluentd到达如何通过tcp发到fluentd> Nxlog是一个日志收集工具, ...
- C基本类型
C基本类型有: char:8位,可添加修改符signed或是unsigned short:16位,同有singed和unsigned int:32位,同有singed和unsigned long:在3 ...
- 【深度学习】keras + tensorflow 实现猫和狗图像分类
本文主要是使用[监督学习]实现一个图像分类器,目的是识别图片是猫还是狗. 从[数据预处理]到 [图片预测]实现一个完整的流程, 当然这个分类在 Kaggle 上已经有人用[迁移学习](VGG,Resn ...
- MySQL事务与锁
MySQL事务与锁 锁的基本概念 锁是计算机协调多个进程或线程并发访问某一资源的机制. 相对其他数据库而言,MySQL的锁机制比较简单,其最显著的特点是不同的存储引擎支持不同的锁机制.比如,MyISA ...
- LeetCode 370. Range Addition (范围加法)$
Assume you have an array of length n initialized with all 0's and are given k update operations. Eac ...
- LeetCode 26. Remove Duplicates from Sorted Array (从有序序列里移除重复项)
Given a sorted array, remove the duplicates in place such that each element appear only once and ret ...
- 想成为一个高效的Web开发者吗?来看看大牛分享的经验吧~ #精选JAVASCRIPT前端开发
想成为一个高效的Web开发者吗?来看看大牛分享的经验吧~ 作为一个软(ku)件(bi)工(de)程(ma)师(nong),你有没有觉得做什么事都没时间?没时间学习新东西,没时间去回顾.整理原来写的烂代 ...
- hive 创建表和导入数据实例
//创建数据库create datebase hive;//创建表create table t_emp(id int,name string,age int,dept_name string,like ...