Implementing a Linux WC command with Python

Source: Internet
Author: User
Tags python script

#!/usr/bin/env python "" "file name: opt_wc.py" ""  import osimport sysfrom  Optparse import optionparser def opt ():    parser =  Optionparser ()      parser.add_option ("-C",  "--chars",                        dest =  "Chars",                       action =  "Store_true",                       default  = False,                       help =  "Only count chars.")     parser.add_option ("-W",   " --words ",                       dest =  "Words",                       action =  "Store_ True ",                       default = False,                       help =  "only  Count words. ")     parser.add_option ("-L",  "--lines",                       dest =  " Lines ",                       action =  "Store_true",                       default = False,                        help =  "Only count lines.")     parser.add_option ("-N",  "--nototal",                        dest =   "Nototal",                        action =  "Store_true",                         Default = false,                       help =   "Not print total count.")     options, args = parser.parse_args ()      return  options, args def get_count (data):     chars = len (data)     words = len (Data.split ())     lines =  Data.count (' \ n ')     RETURN LINES, WORDS, CHARS DEF PRINT_WC ( OPTIONS, LINES, WORDS, CHARS, FN):    if options.lines:         print lines,    if options.words:         print words,    if options.chars :         PRINT CHARS,    PRINT FN&NBSp;def main ():     options, args = opt ()     if  not  (Options.chars or options.words or options.lines):         options.chars, options.words, options.lines = 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_count (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:&nbSp;is a directory. "  % fn            else:                 sys.stderr.write ("%s: No  such file or directory.\n " % FN)          if len (args)  >1:            if   not options.total:                 PRINT_WC (options, total_lines, total_words, total_chars,  ' total ')      else:        data =  Sys.stdin.read ()         fn =  ""          lines, words, chars = get_count (data)        &nBSP; PRINT_WC (OPTIONS, LINES, WORDS, CHARS, FN)  if __name__ ==  ' _ _main__ ':     main ()


The main use of the Optparse in the Optionparser module, custom options. Here, only the-l,-c,-w three commands are defined, corresponding to the-l,-w,-c three commands of the WC command, respectively, the count of rows, the number of words and the number of characters. The Python version of the WC command can also achieve the effect of the Linux command WC with the Optionparser module custom command.


Optparse usage:

1. Create a Optionparser object, such as parser = Optionparser ()

2. Call the Add_option () method of the parser object, and customize the options:

Parser.add_option ("-C",

"--chars",

Dest = "Chars",

Action = "Store_true",

Default = False,

Help = "only count chars.")

"-C" and "--chars" are the difference between a short command and a long command.

The value stored by the Dest object.

How the action is saved when the command is interpreted. There are generally three default cases, "store", "Store_true", "Stor_false":

When it is "store", if there is a value after the command, it will be saved in the Dest declaration of the storage variables, such as <your_script>-c/etc/hosts; The "/etc/hosts" is saved in the chars.

When it is "store_true", if the-C command is interpreted, then ' chars ': true;

When it is "Store_false", if the-C command is interpreted, then ' chars ': false;

Default value of the Default:action parameter

Help: equivalent to helping information


3. When all commands that require customization are ready, you can call the Parser.parse_args () method, which returns two values, options, and args.

The options is a dictionary dict form, the key of this dictionary is the dest value of the above custom command. For example, in this example, you customize the-c,-w,-l three command options, their action is "store_true", when the input has a command, it corresponds to the value of the stored variable is True, so when the Python opt_wc.py-c in this way executes the script , you will get the value of the options: [' chars ': True, ' words ': flase, ' lines ': False]. Through this dictionary, you can see what commands the script will handle.


The second variable returned by the Parser.parse_args () method is args, which is a list of lists that save the command line parameter values other than-c,-l and--chars,--lines, such as short commands and long commands. For example, the command line Python opt_wc.py-l/etc/hosts/etc/passwd, then args = ['/etc/hosts ', '/etc/passwd '], the args returned by the Parse_args () method can know the script Files that need to be processed.


Extended version of the WC command: Added the option of-N,--nototal, if you add the-n option at the command line, enter multiple files without counting the totals.


Python script Run Effect:


Default count of rows, characters, words:

650) this.width=650; "Src=" Http://s1.51cto.com/wyfs02/M00/88/85/wKiom1f6VefgDIfEAAAmOr8Iq0E853.png-wh_500x0-wm_3 -wmp_4-s_2686180972.png "style=" Float:none; "title=" Default statistic All "alt=" Wkiom1f6vefgdifeaaamor8iq0e853.png-wh_50 "/>


Statistics two files:

650) this.width=650; "Src=" Http://s4.51cto.com/wyfs02/M01/88/81/wKioL1f6VejQc8yBAABAj4XmF-k892.png-wh_500x0-wm_3 -wmp_4-s_3629358304.png "style=" Float:none; "title=" Statistics two Files "alt=" Wkiol1f6vejqc8ybaabaj4xmf-k892.png-wh_50 "/>


Count rows only:

650) this.width=650; "Src=" Http://s4.51cto.com/wyfs02/M00/88/85/wKiom1f6VeiDi598AAA5bfe8KlM311.png-wh_500x0-wm_3 -wmp_4-s_394795892.png "style=" Float:none; "title=" counts only Rows "alt=" Wkiom1f6veidi598aaa5bfe8klm311.png-wh_50 "/>


Output error Handling:

650) this.width=650; "Src=" Http://s5.51cto.com/wyfs02/M02/88/81/wKioL1f6VemyQQc0AAAp2Vyozug153.png-wh_500x0-wm_3 -wmp_4-s_1197677645.png "style=" Float:none; "title=" Error Handling "alt=" Wkiol1f6vemyqqc0aaap2vyozug153.png-wh_50 "/>"


This article is from the "dayandnight" blog, make sure to keep this source http://hellocjq.blog.51cto.com/11336969/1860410

Implementing a Linux WC command with Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.