clize, getopt
This commit is contained in:
parent
e2f249340c
commit
f001692714
|
@ -0,0 +1,62 @@
|
|||
# Deux petits trucs utiles pour la CLI
|
||||
|
||||
[clize](https://pypi.org/project/clize/) : ça convertit une fonction en module avec aide, en parsant les arguments.
|
||||
|
||||
Par exemple :
|
||||
|
||||
```python
|
||||
from clize import run
|
||||
|
||||
def translate(file_path):
|
||||
"""Fonction de translation: convertit un fichier reçu en entrée vers un fichier output-<timestamp>.txt
|
||||
|
||||
:param file_path: Le chemin relatif ou absolu vers le fichier.
|
||||
"""
|
||||
pass
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(translate)
|
||||
|
||||
λ python translate.py --help
|
||||
Usage: translate.py file-path
|
||||
|
||||
Fonction de translation: convertit un fichier reçu en entrée vers un fichier output-<timestamp>.txt
|
||||
|
||||
Arguments:
|
||||
file-path Le chemin relatif ou absolu vers le fichier.
|
||||
|
||||
Other actions:
|
||||
-h, --help Show the help
|
||||
|
||||
λ python translate.py
|
||||
translate.py: Missing required arguments: file-path
|
||||
Usage: translate.py file-path
|
||||
```
|
||||
|
||||
Le [deuxième](http://sametmax.com/la-plus-belle-maniere-de-parser-les-arguments-de-script-en-python/) est un chouia plus complexe, mais tout aussi efficace: on écrit la doc et ça génère la récupération des arguments pour la CLI.
|
||||
|
||||
Magique.
|
||||
|
||||
Si on voulait faire la même chose avec getopt :
|
||||
|
||||
```python
|
||||
import getopt, sys
|
||||
|
||||
try:
|
||||
opts, args = getopt.getopt(sys.argv[1:], "hf", ["help", "file_path"])
|
||||
except getopt.GetoptError as err:
|
||||
print(err)
|
||||
usage()
|
||||
sys.exit(2)
|
||||
|
||||
file_path = None
|
||||
|
||||
for o, a in opts:
|
||||
if o in ("-f", "--file-path"):
|
||||
translate(a)
|
||||
elif o in ("-h", "--help"):
|
||||
usage()
|
||||
sys.exit()
|
||||
else:
|
||||
assert False, "unhandled option"
|
||||
```
|
Loading…
Reference in New Issue