Repository with sources and generator of https://larlet.fr/david/ https://larlet.fr/david/
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

article.md 5.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. title: Un template python pour parser des arguments
  2. slug: un-template-python-pour-parser-des-arguments
  3. date: 2006-02-18 17:56:10
  4. type: post
  5. vignette: images/logos/python_nouveau.png
  6. contextual_title1: Bonnes pratiques et astuces Python
  7. contextual_url1: 20080511-bonnes-pratiques-et-astuces-python
  8. contextual_title2: Benchmarks map, filter vs. list-comprehensions
  9. contextual_url2: 20061025-benchmarks-map-filter-vs-list-comprehensions
  10. contextual_title3: Python : lisibilité vs simplicité
  11. contextual_url3: 20060425-python-et-underscore
  12. <p>En réaction au billet de <a href="http://blog.virgule.info/2006/02/17/137-convertisseur-em-vers-pixels">mat qui a codé un convertisseur em vers pixels</a>. Je me demande souvent si la méthode que j'emploie est la plus pertinente pour parser des arguments en ligne de commande lorsque je crée des petits scripts en python. Voici le template que j'utilise souvent, toutes les remarques en commentaire sont les bienvenues&nbsp;!</p>
  13. <pre>#!/usr/bin/python
  14. # -*- coding: iso-8859-1 -*-
  15. """
  16. Explain what program do.
  17. """
  18. import os
  19. import sys
  20. from textwrap import wrap
  21. from getopt import getopt
  22. # Global default settings, had to be get/set with appopriate functions
  23. settings = {
  24. "verbose" : False, # -v option
  25. "other_option" : "" # -o: option
  26. }
  27. def set_settings(key, value): settings[key] = value
  28. def get_settings(key): return settings[key]
  29. def verify_arguments_existence():
  30. """ For each command line argument, check existence if necessary """
  31. if get_settings("other_option") == "":
  32. set_settings("other_option", "default")
  33. def parse_arguments():
  34. shortopts = "".join([opt[0] for opt in options])
  35. longopts = [opt[1] for opt in options]
  36. opts, args = getopt(sys.argv[1:], shortopts, longopts)
  37. for opt, optarg in opts:
  38. for tuple in options:
  39. short = "-" + tuple[0][:1]
  40. long = "--" + tuple[1]
  41. if long.endswith("="):
  42. long = long[:-1]
  43. if opt in [short, long]:
  44. tuple[2](optarg)
  45. break
  46. def print_help(*args):
  47. print "USAGE:
  48. %s [options]
  49. " % sys.argv[0]
  50. print "OPTIONS:"
  51. for short, long, func, doc in options:
  52. print
  53. if short[-1] == ":":
  54. print " -%s filename, --%sfilename" % (short[:1], long)
  55. else:
  56. print " -%s, --%s" % (short[:1], long)
  57. for line in wrap(doc):
  58. print " %s" % line
  59. print "
  60. EXAMPLE:"
  61. print " %s -v -o:argument
  62. " % sys.argv[0]
  63. sys.exit(0)
  64. # Syntax : short option, long option, action, help
  65. options = [
  66. ("h", "help", print_help,
  67. "Print out this usage summary."),
  68. ("v", "verbose", lambda optarg: set_settings("verbose", True),
  69. "Write output informations (not only errors)."),
  70. ("o:", "other-option=", lambda optarg: set_settings("other_option", optarg),
  71. "Another option for the template.")
  72. ]
  73. def main():
  74. """ Main function, deals with arguments and launch program"""
  75. # Usual verifications and warnings
  76. if not sys.argv[1:]:
  77. sys.stdout.write("Sorry: you must specify at least an argument
  78. ")
  79. sys.stdout.write("More help avalaible with -h or --help option
  80. ")
  81. sys.exit(0)
  82. parse_arguments()
  83. verify_arguments_existence()
  84. # THE program :-)
  85. if get_settings("verbose"):
  86. print "Hello verbose Word !"
  87. else:
  88. print "Hello Word !"
  89. if __name__ == '__main__':
  90. main()</pre>
  91. <p>Et la même chose en <a href="http://vrac.biologeek.com/template_python.txt">fichier texte</a> si vous souhaitez l'utiliser.</p>
  92. <p><strong>[edit]</strong>&nbsp;: <del>J'ai encore perdu une occasion de me taire</del> Je suis heureux d'avoir appris l'existence d'un nouveau module, effectivement <strong>optparse</strong> permet de parser les arguments en ligne de commande très facilement du coup mon template ne sert plus à rien ;-)</p>
  93. <p>Voila ce que ce même template donnerait avec l'utilisation de ce module&nbsp;:</p>
  94. <pre>#!/usr/bin/python
  95. # -*- coding: iso-8859-1 -*-
  96. """
  97. Explain what program do.
  98. """
  99. import os
  100. import sys
  101. from optparse import OptionParser
  102. def main():
  103. """ Main function, deals with arguments and launch program"""
  104. # Usual verifications and warnings
  105. if not sys.argv[1:]:
  106. sys.stdout.write("Sorry: you must specify at least an argument
  107. ")
  108. sys.stdout.write("More help avalaible with -h or --help option
  109. ")
  110. sys.exit(0)
  111. parser = OptionParser()
  112. parser.add_option("-v", "--verbose", action="store_true",
  113. help="Write output informations (not only errors).",
  114. default=False)
  115. parser.add_option("-f", "--file", help="Create a xxx file.")
  116. (options, args) = parser.parse_args()
  117. # THE program :-)
  118. if options.verbose:
  119. print "Hello verbose Word !"
  120. else:
  121. print "Hello Word !"
  122. if __name__ == '__main__':
  123. main()</pre>
  124. <p>Simple, concis, bref à utiliser. <a href="http://www.la-grange.net/2003/10/29.html#python">Karl en parlait déjà</a> il y a plus de deux ans...</p>