File tree Expand file tree Collapse file tree
implement-shell-tools/implement-shell-tools-python/cat Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ #!/usr/bin/env python3
2+ import sys
3+ import os
4+
5+ global_line_counter = 1
6+
7+ def print_file (file_path , options ):
8+ global global_line_counter
9+ try :
10+ with open (file_path , "r" , encoding = "utf-8" ) as f :
11+ content = f .read ()
12+
13+ lines = content .split ("\n " )
14+ if lines and lines [- 1 ] == "" :
15+ lines .pop ()
16+
17+ for line in lines :
18+ prefix = ""
19+
20+ should_number = (
21+ options ["number_mode" ] == "all" or
22+ (options ["number_mode" ] == "non-empty" and line .strip () != "" )
23+ )
24+
25+ if should_number :
26+ prefix = f"{ global_line_counter :6} \t "
27+ global_line_counter += 1
28+
29+ sys .stdout .write (prefix + line + "\n " )
30+
31+ except Exception as e :
32+ print (f"cat: { file_path } : { e } " , file = sys .stderr )
33+ sys .exit (1 )
34+
35+
36+ def main ():
37+ global global_line_counter
38+ args = sys .argv [1 :]
39+
40+ options = {"number_mode" : "off" }
41+ files = []
42+
43+ for arg in args :
44+ if arg == "-n" :
45+ options ["number_mode" ] = "all"
46+ elif arg == "-b" :
47+ options ["number_mode" ] = "non-empty"
48+ else :
49+ files .append (arg )
50+
51+ if not files :
52+ print ("cat: missing file operand" , file = sys .stderr )
53+ sys .exit (1 )
54+
55+ for file_path in files :
56+ global_line_counter = 1
57+ print_file (file_path , options )
58+
59+
60+ if __name__ == "__main__" :
61+ main ()
You can’t perform that action at this time.
0 commit comments