Repository with sources and generator of https://larlet.fr/david/ https://larlet.fr/david/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. <!doctype html>
  2. <html lang=fr>
  3. <head>
  4. <!-- Always define the charset before the title -->
  5. <meta charset=utf-8>
  6. <title>Un template python pour parser des arguments — Biologeek — David Larlet</title>
  7. <!-- Define a viewport to mobile devices to use - telling the browser to assume that the page is as wide as the device (width=device-width) and setting the initial page zoom level to be 1 (initial-scale=1.0) -->
  8. <meta name="viewport" content="width=device-width, initial-scale=1"/>
  9. <!-- Fake favicon, to avoid extra request to the server -->
  10. <link rel="icon" href="data:;base64,iVBORw0KGgo=">
  11. <link type="application/atom+xml" rel="alternate" title="Feed" href="/david/log/" />
  12. <link rel="manifest" href="/manifest.json">
  13. <link rel="stylesheet" href="/static/david/css/larlet-david-_J6Rv.css" data-instant-track />
  14. <noscript>
  15. <style type="text/css">
  16. /* Otherwise fonts are loaded by JS for faster initial rendering. See scripts at the bottom. */
  17. body {
  18. font-family: 'EquityTextB', serif;
  19. }
  20. h1, h2, h3, h4, h5, h6, time, nav a, nav a:link, nav a:visited {
  21. font-family: 'EquityCapsB', sans-serif;
  22. font-variant: normal;
  23. }
  24. </style>
  25. </noscript>
  26. <!-- Canonical URL for SEO purposes -->
  27. <link rel="canonical" href="https://larlet.fr/david/biologeek/archives/20060218-un-template-python-pour-parser-des-arguments">
  28. </head>
  29. <body>
  30. <div>
  31. <header>
  32. <nav>
  33. <p>
  34. <small>
  35. Je suis <a href="/david/" title="Profil public">David Larlet</a>, <a href="/david/pro/" title="Activité professionnelle">artisan</a> du web qui vous <a href="/david/pro/accompagnement/" title="Activité d’accompagnement">accompagne</a><span class="more-infos"> dans l’acquisition de savoirs pour concevoir des <a href="/david/pro/produits-essentiels/" title="Qu’est-ce qu’un produit essentiel ?">produits essentiels</a></span>. <span class="more-more-infos">Discutons ensemble d’une <a href="/david/pro/devis/" title="En savoir plus">non-demande de devis</a>.</span> Je partage ici mes <a href="/david/blog/" title="Expériences bienveillantes">réflexions</a> et <a href="/david/correspondances/2017/" title="Lettres hebdomadaires">correspondances</a>.
  36. </small>
  37. </p>
  38. </nav>
  39. </header>
  40. <section>
  41. <h1 property="schema:name">Un template python pour parser des arguments</h1>
  42. <article typeof="schema:BlogPosting">
  43. <div property="schema:articleBody">
  44. <img src="/static/david/biologeek/images/logos/python_nouveau.png" alt="vignette" style="float:left; margin: 0.5em 1em;" property="schema:thumbnailUrl" />
  45. <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>
  46. <pre>#!/usr/bin/python
  47. # -*- coding: iso-8859-1 -*-
  48. """
  49. Explain what program do.
  50. """
  51. import os
  52. import sys
  53. from textwrap import wrap
  54. from getopt import getopt
  55. # Global default settings, had to be get/set with appopriate functions
  56. settings = {
  57. "verbose" : False, # -v option
  58. "other_option" : "" # -o: option
  59. }
  60. def set_settings(key, value): settings[key] = value
  61. def get_settings(key): return settings[key]
  62. def verify_arguments_existence():
  63. """ For each command line argument, check existence if necessary """
  64. if get_settings("other_option") == "":
  65. set_settings("other_option", "default")
  66. def parse_arguments():
  67. shortopts = "".join([opt[0] for opt in options])
  68. longopts = [opt[1] for opt in options]
  69. opts, args = getopt(sys.argv[1:], shortopts, longopts)
  70. for opt, optarg in opts:
  71. for tuple in options:
  72. short = "-" + tuple[0][:1]
  73. long = "--" + tuple[1]
  74. if long.endswith("="):
  75. long = long[:-1]
  76. if opt in [short, long]:
  77. tuple[2](optarg)
  78. break
  79. def print_help(*args):
  80. print "USAGE:
  81. %s [options]
  82. " % sys.argv[0]
  83. print "OPTIONS:"
  84. for short, long, func, doc in options:
  85. print
  86. if short[-1] == ":":
  87. print " -%s filename, --%sfilename" % (short[:1], long)
  88. else:
  89. print " -%s, --%s" % (short[:1], long)
  90. for line in wrap(doc):
  91. print " %s" % line
  92. print "
  93. EXAMPLE:"
  94. print " %s -v -o:argument
  95. " % sys.argv[0]
  96. sys.exit(0)
  97. # Syntax : short option, long option, action, help
  98. options = [
  99. ("h", "help", print_help,
  100. "Print out this usage summary."),
  101. ("v", "verbose", lambda optarg: set_settings("verbose", True),
  102. "Write output informations (not only errors)."),
  103. ("o:", "other-option=", lambda optarg: set_settings("other_option", optarg),
  104. "Another option for the template.")
  105. ]
  106. def main():
  107. """ Main function, deals with arguments and launch program"""
  108. # Usual verifications and warnings
  109. if not sys.argv[1:]:
  110. sys.stdout.write("Sorry: you must specify at least an argument
  111. ")
  112. sys.stdout.write("More help avalaible with -h or --help option
  113. ")
  114. sys.exit(0)
  115. parse_arguments()
  116. verify_arguments_existence()
  117. # THE program :-)
  118. if get_settings("verbose"):
  119. print "Hello verbose Word !"
  120. else:
  121. print "Hello Word !"
  122. if __name__ == '__main__':
  123. main()</pre>
  124. <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>
  125. <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>
  126. <p>Voila ce que ce même template donnerait avec l'utilisation de ce module&nbsp;:</p>
  127. <pre>#!/usr/bin/python
  128. # -*- coding: iso-8859-1 -*-
  129. """
  130. Explain what program do.
  131. """
  132. import os
  133. import sys
  134. from optparse import OptionParser
  135. def main():
  136. """ Main function, deals with arguments and launch program"""
  137. # Usual verifications and warnings
  138. if not sys.argv[1:]:
  139. sys.stdout.write("Sorry: you must specify at least an argument
  140. ")
  141. sys.stdout.write("More help avalaible with -h or --help option
  142. ")
  143. sys.exit(0)
  144. parser = OptionParser()
  145. parser.add_option("-v", "--verbose", action="store_true",
  146. help="Write output informations (not only errors).",
  147. default=False)
  148. parser.add_option("-f", "--file", help="Create a xxx file.")
  149. (options, args) = parser.parse_args()
  150. # THE program :-)
  151. if options.verbose:
  152. print "Hello verbose Word !"
  153. else:
  154. print "Hello Word !"
  155. if __name__ == '__main__':
  156. main()</pre>
  157. <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>
  158. </div>
  159. </article>
  160. <footer>
  161. <h6 property="schema:datePublished">— 18/02/2006</h6>
  162. </footer>
  163. </section>
  164. <section>
  165. <div>
  166. <h3>Articles peut-être en rapport</h3>
  167. <ul>
  168. <li><a href="/david/biologeek/archives/20080511-bonnes-pratiques-et-astuces-python/" title="Accès à Bonnes pratiques et astuces Python">Bonnes pratiques et astuces Python</a></li>
  169. <li><a href="/david/biologeek/archives/20061025-benchmarks-map-filter-vs-list-comprehensions/" title="Accès à Benchmarks map, filter vs. list-comprehensions">Benchmarks map, filter vs. list-comprehensions</a></li>
  170. <li><a href="/david/biologeek/archives/20060425-python-et-underscore/" title="Accès à Python : lisibilité vs simplicité">Python : lisibilité vs simplicité</a></li>
  171. </ul>
  172. </div>
  173. </section>
  174. <section>
  175. <div id="comments">
  176. <h3>Commentaires</h3>
  177. <div class="comment" typeof="schema:UserComments">
  178. <p class="comment-meta">
  179. <span class="comment-author" property="schema:creator">mat</span> le <span class="comment-date" property="schema:commentTime">18/02/2006</span> :
  180. </p>
  181. <div class="comment-content" property="schema:commentText">
  182. <p>Bah moi j'ai fait betement en copiant collant la doc, ne connaissant que tres peu python et n'ayant pas envie de me prendre la tete avec ca (le script était deja fini quand j'ai rajouté la gestion des arguments)<br />
  183. <br />
  184. La doc python mentionnait optparse, qui a l'air plus complet, tu devrais ptet plutot zieuter par la pour un truc un peu plus complet et plus robuste...</p>
  185. </div>
  186. </div>
  187. <div class="comment" typeof="schema:UserComments">
  188. <p class="comment-meta">
  189. <span class="comment-author" property="schema:creator">David, biologeek</span> le <span class="comment-date" property="schema:commentTime">18/02/2006</span> :
  190. </p>
  191. <div class="comment-content" property="schema:commentText">
  192. <p>« optparse is a more convenient, flexible, and powerful library for parsing command-line options than getopt. »<br />
  193. <br />
  194. Ok je vais jetter un œil à ça, un edit est très probable :)</p>
  195. </div>
  196. </div>
  197. <div class="comment" typeof="schema:UserComments">
  198. <p class="comment-meta">
  199. <span class="comment-author" property="schema:creator">bubu</span> le <span class="comment-date" property="schema:commentTime">20/08/2008</span> :
  200. </p>
  201. <div class="comment-content" property="schema:commentText">
  202. <p>Helas optparse n&#39;est pas internationalisé, et pose des problemes avec les caracteres speciaux.</p>
  203. </div>
  204. </div>
  205. </div>
  206. </section>
  207. <footer>
  208. <nav>
  209. <p>
  210. <small>
  211. Je réponds quasiment toujours aux <a href="m&#x61;ilto:d&#x61;vid%40l&#x61;rlet&#46;fr" title="Envoyer un email">emails</a> (<a href="/david/signature/" title="Ma signature actuelle avec possibilité de chiffrement">signés</a>) et vous pouvez me rencontrer à Montréal. <span class="more-infos">N’hésitez pas à <a href="/david/log/" title="Être tenu informé des mises à jour">vous abonner</a> pour être tenu informé des publications récentes.</span>
  212. </small>
  213. </p>
  214. </nav>
  215. </footer>
  216. </div>
  217. <script src="/static/david/js/larlet-david-3ee43f.js" data-no-instant></script>
  218. <script data-no-instant>InstantClick.init()</script>
  219. </body>
  220. </html>