File tree Expand file tree Collapse file tree
implement-shell-tools/cat Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ #!/usr/bin/env python3
2+
3+ import sys
4+
5+ def cat_file (file , options , line_number ):
6+ try :
7+ with open (file , 'r' , encoding = 'utf-8' ) as f :
8+ lines = f .readlines ()
9+
10+ for line in lines :
11+ if options ['number_non_blank' ] and line .strip ():
12+ print (f"{ line_number :6} \t { line } " , end = '' )
13+ line_number += 1
14+ elif options ['number_all' ]:
15+ print (f"{ line_number :6} \t { line } " , end = '' )
16+ line_number += 1
17+ else :
18+ print (line , end = '' )
19+
20+ return line_number
21+ except FileNotFoundError :
22+ print (f"cat: { file } : No such file or directory" , file = sys .stderr )
23+ sys .exit (1 )
24+
25+ def main ():
26+ args = sys .argv [1 :]
27+ options = {
28+ 'number_all' : False ,
29+ 'number_non_blank' : False ,
30+ }
31+
32+ files = []
33+
34+ for arg in args :
35+ if arg == '-n' :
36+ options ['number_all' ] = True
37+ elif arg == '-b' :
38+ options ['number_non_blank' ] = True
39+ else :
40+ files .append (arg )
41+
42+ if not files :
43+ print ("Usage: cat [-n | -b] <file>..." , file = sys .stderr )
44+ sys .exit (1 )
45+
46+ line_number = 1
47+ for file in files :
48+ line_number = cat_file (file , options , line_number )
49+
50+ if __name__ == "__main__" :
51+ main ()
You can’t perform that action at this time.
0 commit comments