File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
implement-shell-tools/ls/sample-files Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 1+ #!/usr/bin/env python3
2+ import argparse
3+ import os
4+
5+ def list_directory (dir_path , show_all ):
6+ if not os .path .exists (dir_path ):
7+ print (f"ls: cannot access '{ dir_path } ': No such file or directory" )
8+ return
9+
10+ if os .path .isfile (dir_path ):
11+ print (dir_path )
12+ return
13+
14+ try :
15+ entries = os .listdir (dir_path )
16+ except PermissionError :
17+ print (f"ls: cannot access '{ dir_path } ': Permission denied" )
18+ return
19+
20+ if not show_all :
21+ entries = [e for e in entries if not e .startswith ("." )]
22+ else :
23+ entries = ["." , ".." ] + entries
24+
25+ entries .sort ()
26+ for e in entries :
27+ print (e )
28+
29+ def main ():
30+ parser = argparse .ArgumentParser (description = "Custom implementation of ls" )
31+ parser .add_argument ("-1" , action = "store_true" , help = "list one file per line (default)" )
32+ parser .add_argument ("-a" , "--all" , action = "store_true" , help = "include hidden files" )
33+ parser .add_argument ("dir" , nargs = "?" , default = "." , help = "directory to list" )
34+
35+ args = parser .parse_args ()
36+
37+ list_directory (args .dir , args .all )
38+
39+ if __name__ == "__main__" :
40+ main ()
You can’t perform that action at this time.
0 commit comments