Created
August 13, 2022 22:57
-
-
Save Neboer/3a8bf68717a88c353af645b24b6e79dc to your computer and use it in GitHub Desktop.
sls,一个全平台支持的简单ls命令,主要用于解决Windows操作系统里没有合适的、支持终端编码输出的ls命令的问题。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
from pathlib import Path | |
import os | |
from os import scandir | |
from sys import stderr, exit | |
class PseudoDirEntry: | |
def __init__(self, path): | |
if not Path(path).exists(): | |
raise FileNotFoundError | |
self.path = os.path.realpath(path) | |
self.name = os.path.basename(self.path) | |
self.is_dir = os.path.isdir(self.path) | |
def is_file(self): | |
return not self.is_dir | |
parser = argparse.ArgumentParser(description='Neboer的简单ls命令。') | |
parser.add_argument("-l", action="store_true", help="显示全路径,默认的路径显示方式与path是否绝对相一致") | |
parser.add_argument("-n", action="store_true", help="仅显示文件名,默认的路径显示方式与path是否绝对相一致") | |
parser.add_argument("-d", action="store_true", help="仅列出文件夹,默认全列出") | |
parser.add_argument("-f", action="store_true", help="仅列出文件,默认全列出") | |
parser.add_argument("-o", action="store_true", help="不访问文件夹内容,将传入的路径视为需要显示的结果本身,类似ls -d,在传入一个文件路径时,此选项总是生效的。") | |
parser.add_argument("path", type=str, default=".", help="路径", nargs="?") | |
args = parser.parse_args() | |
entries_need_proceed = [] | |
try: | |
input_entry = PseudoDirEntry(args.path) | |
except FileNotFoundError: | |
print(f"目标文件或文件夹\"{args.path}\"不存在",file=stderr) | |
exit(-1) | |
if input_entry.is_file() or args.o: | |
entries_need_proceed = [input_entry] | |
else: | |
entries_need_proceed = scandir(args.path) | |
if args.d: | |
useful_dir_content = filter(lambda entry: not entry.is_file(), entries_need_proceed) | |
elif args.f: | |
useful_dir_content = filter(lambda entry: entry.is_file(), entries_need_proceed) | |
else: | |
useful_dir_content = entries_need_proceed | |
for entry in useful_dir_content: | |
if args.l: | |
print(Path(entry.path).resolve()) | |
elif args.n: | |
print(entry.name) | |
else: | |
print(entry.path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment