[Python] python 中参数用法大全 →→→→→进入此内容的聊天室

来自 , 2021-02-16, 写在 Python, 查看 182 次.
URL http://www.code666.cn/view/f6a673f0
  1. #!/usr/bin/env python
  2. #
  3. # [SNIPPET_NAME: Arguments]
  4. # [SNIPPET_CATEGORIES: Python Core]
  5. # [SNIPPET_DESCRIPTION: GNU style arguments]
  6. # [SNIPPET_AUTHOR: Jurjen Stellingwerff <jurjen@stwerff.xs4all.nl>]
  7. # [SNIPPET_LICENSE: GPL]
  8.  
  9. # example arguments.py
  10.  
  11. import sys
  12.  
  13.  
  14. program = "arguments.py"
  15. version = "0.1"
  16.  
  17.  
  18. def indent(size, text):
  19.     """ Indents the lines of a text with 'size' spaces for every newline. """
  20.     i = 0
  21.     res = ""
  22.     for line in text.split("\n"):
  23.         if i > 0:
  24.             res += "\n".ljust(size) + line
  25.         else:
  26.             res += line
  27.         i += 1
  28.     return res
  29.  
  30.  
  31. def show_arguments():
  32.     out = []
  33.     size = 0
  34.     for argument in sorted(arguments):
  35.         show = ""
  36.         function, helptext, parameter = arguments[argument]
  37.         if not helptext:
  38.             continue
  39.         if len(argument) > 1:
  40.             show += "    --" + argument
  41.         else:
  42.             show += "-" + argument
  43.         others = False
  44.         for other in sorted(arguments):
  45.             function2, helptext2, parameter2 = arguments[other]
  46.             if function2 == function and other != argument:
  47.                 others = True
  48.                 if len(other) > 1:
  49.                     show += ", --" + other
  50.                     if parameter2:
  51.                         show += "=" + parameter2
  52.                 else:
  53.                     show += ", -" + other
  54.         if parameter and len(argument) > 1:
  55.             show += "=" + parameter
  56.         elif parameter and not others:
  57.             show += " " + parameter
  58.         if len(show) > size and len(show) < 20:
  59.             size = len(show)
  60.         out.append((show, helptext))
  61.     for show, helptext in out:
  62.         if len(show) <= size:
  63.             print ("  %-" + str(size) + "s  %s") % (show, indent(size + 8, helptext))
  64.         else:
  65.             print "  " + show
  66.             print ("   %" + str(size) + "s") % "", indent(size + 8, helptext)
  67.  
  68.  
  69. def unknown_argument(argument):
  70.     """ Show an informative error when encountering unknown arguments """
  71.     print program + ": unrecognized option '" + argument + "'"
  72.     print "Try: `" + program + " --help' for more information"
  73.     sys.exit(2)
  74.  
  75.  
  76. def parse_arguments():
  77.     """ Reads all the arguments from argv and interprets them in a GNU arguments style """
  78.     i = 0
  79.     paramfunction = None
  80.     for argument in sys.argv:
  81.         i += 1
  82.         if i == 1:
  83.             continue
  84.         if paramfunction:
  85.             paramfunction(argument)
  86.             paramfunction = None
  87.         elif argument.startswith("--"):
  88.             pos = argument.find("=")
  89.             if pos > -1:
  90.                 try:
  91.                     function, helptext, parameter = arguments[argument[2:pos]]
  92.                     if not parameter:
  93.                         print "Argument '" + argument[2:pos] + "' cannot have a parameter"
  94.                         sys.exit()
  95.                     function(argument[pos + 1:])
  96.                 except KeyError:
  97.                     unknown_argument(argument[:pos])
  98.             else:
  99.                 try:
  100.                     function, helptext, parameter = arguments[argument[2:]]
  101.                     function()
  102.                 except KeyError:
  103.                     unknown_argument(argument)
  104.         elif argument.startswith("-"):
  105.             for pos in range(1, len(argument)):
  106.                 try:
  107.                     function, helptext, parameter = arguments[argument[pos:pos + 1]]
  108.                     if parameter:
  109.                         paramfunction = function
  110.                     else:
  111.                         function()
  112.                 except KeyError:
  113.                     unknown_argument(argument[pos:pos + 1])
  114.         else:
  115.             do_rest_arguments(argument)
  116.  
  117.  
  118. def add_argument(function, help_text=None, parameter=None):
  119.     """ Add information about an argument:
  120.        - function:  function to call when this argument in given
  121.        - help_text: the help text to show on the help page, omit this parameter on arguments with the same function
  122.        - parameter: this argument needs a parameter
  123.    """
  124.     return function, help_text, parameter
  125.  
  126.  
  127. # From here on the actual program code starts
  128.  
  129. def do_help():
  130.     """ Prints a list of arguments for this program. Normally you would change this function to include more info like examples and another program descriptor. """
  131.     print "Usage: " + program + " [OPTION]... [REST]"
  132.     print "Demonstrates python code for GNU style arguments."
  133.     print ""
  134.     print "Mandatory arguments to long options are mandatory for short options too."
  135.     show_arguments()
  136.     print ""
  137.     print "Report arguments bugs to jurjen@stwerff.xs4all.nl"
  138.     print "Python-snippets homepage: <https://code.launchpad.net/python-snippets>"
  139.     exit()
  140.  
  141.  
  142. def do_version():
  143.     """ Show version information of this program """
  144.     print program + " " + version
  145.     print "Copyright (C) 2010 Jurjen Stellingwerff"
  146.     print "Lisense GPL: GNU GPL version 2 or later <http://gnu.org/licenses/gpl.html>."
  147.     print "This is free software: you are free to change and redistribute it."
  148.     print "There is NO WARRENTY, to the extent permittable by law."
  149.     print ""
  150.     print "Written by Jurjen Stellingwerff."
  151.     exit()
  152.  
  153.  
  154. files = []
  155. """ list of files to write to the standard output, can be filled by arguments """
  156.  
  157. verbose = True
  158.  
  159.  
  160. def do_quiet():
  161.     global verbose
  162.     verbose = False
  163.  
  164.  
  165. def do_file(filename):
  166.     global files
  167.     files.append(filename)
  168.  
  169.  
  170. def do_something(argument):
  171.     print argument
  172.  
  173.  
  174. def do_single(argument):
  175.     print argument
  176.  
  177.  
  178. def do_rest_arguments(argument):
  179.     print "Rest:", argument
  180.  
  181.  
  182. arguments = {
  183.     'version' : add_argument(do_version, 'output version information and exit'),
  184.     'h' : add_argument(do_help, 'display this help and exit'),
  185.     '?' : add_argument(do_help),
  186.     'help' : add_argument(do_help),
  187.     'q' : add_argument(do_quiet, "don't print status messages to stdout"),
  188.     'quiet' : add_argument(do_quiet),
  189.     'f' : add_argument(do_file, 'display this file', parameter='FILE'),
  190.     'file' : add_argument(do_file, parameter='FILE'),
  191.     'this-is-a-bit-too-long-argument' : add_argument(do_something, "when arguments get too long the line splits\nand lines can contain newlines", parameter='SOMETHING'),
  192.     's' : add_argument(do_single, "single token argument with a parameter", parameter='SOMETHING')
  193. }
  194.  
  195. parse_arguments()
  196. for filename in files:
  197.     if verbose:
  198.         print "Printing file", filename
  199.     try:
  200.         f = open(filename, 'r')
  201.         for line in f.readlines():
  202.             print line.rstrip()
  203.     except IOError:
  204.         print "No such file: '" + filename + "'"
  205.  
  206.  
  207. # demonstrate the help page when there are no parameters given
  208. # not very useful in an actual program
  209.  
  210. if len(sys.argv) == 1:
  211.     do_help()
  212. #//python/2369

回复 "python 中参数用法大全"

这儿你可以回复上面这条便签

captcha