Skip to content

Commit d443669

Browse files
added python code for the ls command
1 parent 3a31fbf commit d443669

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

  • implement-shell-tools/ls

‎implement-shell-tools/ls/ls.py‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import os
2+
import argparse
3+
4+
def ls(path='.', one_column=False, show_hidden=False):
5+
try:
6+
files = os.listdir(path)
7+
if not show_hidden:
8+
files = [f for f in files if not f.startswith('.')]
9+
files.sort()
10+
11+
if one_column:
12+
print(*files, sep='\n')
13+
else:
14+
print(*files)
15+
except FileNotFoundError:
16+
print(f"ls: cannot access '{path}': No such file or directory")
17+
18+
def main():
19+
parser = argparse.ArgumentParser()
20+
parser.add_argument('-1', action='store_true', help='list one file per line')
21+
parser.add_argument('-a', action='store_true', help='show hidden files')
22+
parser.add_argument('path', nargs='?', default='.', help='directory to list')
23+
args = parser.parse_args()
24+
25+
ls(args.path, args.__dict__['1'], args.a)
26+
27+
if __name__ == "__main__":
28+
main()

0 commit comments

Comments
 (0)