Python's basic code is used here to implement the basic functions of the WC command program under the Linux system.
#!/usr/bin/env python#encoding:utf-8# author:liwei# FUNCTION:WC program by Python from Optparse import Optionparserimpo RT Sys,os def opt (): parser = Optionparser () parser.add_option ('-C ', '--char ', dest= ' chars ', Action= ' Store_true ', Default=false, help= ' only count chars ') Parser.add_option ('-w ', '--word ', dest= ' words ', action= ' store_true ', Default=false, help= ' only count words ') parser.add_option ('-l ', '--line ', Dest= ' lines ', action= ' store_true ', Default=false, help= ' only count Lines ') parser.add_option ('-n ', '--nototal ', dest= ' nototal ', Action= ' Store_true ', Default=false, help= ' don\ ' t print total informatio n ') options, args =Parser.parse_args () return options, args #print optionsdef get_count (data): chars = len (data) words = Len (data.sp Lit ()) lines = Data.count (' \ n ') return lines, words, chars #if not options.chars and not options.words and not optio NS def PRINT_WC (options, lines, words, chars, fn): If options.lines:print lines, if OPTIONS.WORDS:PR int words, if options.chars:print chars, print fn def main (): options, args = opt () if not (optio Ns.lines or Options.words or options.chars): Options.lines, options.words, Options.chars = True, True, true If Args:total_lines, total_words, total_chars = 0, 0, 0 for FN in Args:if Os.path.isfile ( FN): with open (fn) as Fd:data = Fd.read () lines, words, chars = Get_coun T (data) PRINT_WC (options, lines, words, chars, fn) Total_Lines + = lines Total _words + = words Total_chars + = chars elif Os.path.isdir (FN): print >> Sys.stderr, '%s is a director Y '%fn else:sys.stderr.write ('%s:no such file or directory\n '% fn) # only multiple files are calculated when Tota L field if Len (args) > 1 and not OPTIONS.NOTOTAL:PRINT_WC (options, Total_Lines, Total_words, Total_chars , ' total ') Else:fn = ' data = Sys.stdin.read () lines, words, chars = get_count (data) Prin T_WC (options, lines, words, chars, fn) if __name__ = = ' __main__ ': Main ()