python:accueil

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Les deux révisions précédentes Révision précédente
Prochaine révision
Révision précédente
python:accueil [2021/12/25 11:04] – [Divers] add read from stdin phswpython:accueil [2025/09/04 09:32] (Version actuelle) – [Chaînes de caractères] add link phsw
Ligne 17: Ligne 17:
   * [[https://gist.github.com/sloria/7001839|The Best of the Best Practices (BOBP) Guide for Python]]   * [[https://gist.github.com/sloria/7001839|The Best of the Best Practices (BOBP) Guide for Python]]
   * [[https://www.thecodeship.com/patterns/guide-to-python-function-decorators/|A guide to Python's function decorators]]   * [[https://www.thecodeship.com/patterns/guide-to-python-function-decorators/|A guide to Python's function decorators]]
 +  * [[https://www.nicholashairs.com/posts/major-changes-between-python-versions/|Summary of Major Changes Between Python Versions]]
  
   * [[https://stackoverflow.com/questions/31375656/how-to-draw-the-paths-of-a-networkx-graph-using-different-colours]]   * [[https://stackoverflow.com/questions/31375656/how-to-draw-the-paths-of-a-networkx-graph-using-different-colours]]
Ligne 57: Ligne 58:
  
 config_file = open("file.yaml", 'r') config_file = open("file.yaml", 'r')
-config = yaml.load(config_file)+config = yaml.safe_load(config_file)
 </code> </code>
 ''config'' est alors un dictionnaire contenant toutes les clés du fichier Yaml. ''config'' est alors un dictionnaire contenant toutes les clés du fichier Yaml.
 +
 +Voir [[https://github.com/yaml/pyyaml/wiki/PyYAML-yaml.load(input)-Deprecation|la note]] sur le dépôt pour les différents //loaders//.
  
  
Ligne 90: Ligne 93:
  
 ==== argparse ==== ==== argparse ====
 +
 +  * https://docs.python.org/3/library/argparse.html
  
 Permet de gérer facilement les arguments passés à un script, et générer la documentation qui va avec. Permet de gérer facilement les arguments passés à un script, et générer la documentation qui va avec.
Ligne 98: Ligne 103:
 cli_parser.add_argument("config_file", help="Configuration file in YAML format") cli_parser.add_argument("config_file", help="Configuration file in YAML format")
 cli_parser.add_argument("nb_cores_per_numa", help="Number of cores per NUMA node", type=int) cli_parser.add_argument("nb_cores_per_numa", help="Number of cores per NUMA node", type=int)
-args = cli_parser.parse_args();+args = cli_parser.parse_args()
 </code> </code>
 ''args'' est un objet contenant les paramètres passés en arguments du script (par exemple: ''args.config_file''). ''args'' est un objet contenant les paramètres passés en arguments du script (par exemple: ''args.config_file'').
 +
 +Pour avoir un paramètre optionnel avec une valeur par défaut :
 +<code python>
 +cli_parser.add_argument("b", help="Block size", type=int, nargs="?", default=320)
 +</code>
 +
  
  
Ligne 168: Ligne 179:
     writer.writerows(someiterable)     writer.writerows(someiterable)
 </code> </code>
 +
 +Il est possible d'écrire sur la sortie standard en utilisant le fichier ''sys.stdout''.
  
  
Ligne 176: Ligne 189:
 next(reader) next(reader)
 </code> </code>
 +
 +
 +=== Lire l'entrée standard ou un fichier ===
 +
 +[[https://stackoverflow.com/questions/1450393/how-do-i-read-from-stdin|Source]]
 +
 +<code python>
 +import sys
 +
 +
 +f = open(sys.argv[1]) if len(sys.argv) == 2 else sys.stdin
 +
 +# ... work with f ...
 +
 +if len(sys.argv) == 2:
 +    f.close()
 +</code>
 +
  
  
  
 ==== Ecrire sur stderr ==== ==== Ecrire sur stderr ====
 +
 +  * [[https://eli.thegreenplace.net/2015/redirecting-all-kinds-of-stdout-in-python/|Redirecting all kinds of stdout in Python]]
  
 <code python> <code python>
Ligne 269: Ligne 302:
 === Formatage de chaînes de caractères === === Formatage de chaînes de caractères ===
  
-[[https://pyformat.info/]]+[[https://pyformat.info/]], [[https://fstring.help/cheat/]]
  
 Il faut doubler les accolades pour qu'elles soient ignorées par Python: Il faut doubler les accolades pour qu'elles soient ignorées par Python:
Ligne 349: Ligne 382:
 </code> </code>
  
 +
 +
 +=== Trouver le préfixe commun ===
 +
 +  * [[https://stackoverflow.com/questions/6718196/determine-prefix-from-a-set-of-similar-strings]]
 +  * https://docs.python.org/3/library/os.path.html#os.path.commonprefix
 +
 +<code python>
 +import os
 +
 +os.path.commonprefix([str1, str2])
 +</code>
 +
 +
 +=== Connaître la langue d'un texte ===
 +
 +  * [[https://stackoverflow.com/questions/39142778/how-to-determine-the-language-of-a-piece-of-text/47106810]]
 +
 +L'installation de Polyglot est un peu particulière ([[https://stackoverflow.com/questions/64886067/polyglot-importerror-cannot-import-name-locale-from-icu|source]]) :
 +<code bash>
 +pip install numpy six icu
 +pip install pyicu
 +pip install pycld2
 +pip install morfessor
 +</code>
 +<code python>
 +from polyglot.text import Text
 +if Text(txt).language.code not in ["en", "fr"]:
 +    printf("...")
 +</code>
  
  
Ligne 416: Ligne 479:
  
  
 +=== Mesurer des durées ===
 +
 +[[https://stackoverflow.com/questions/7370801/how-do-i-measure-elapsed-time-in-python|Source]]
 +
 +<code python>
 +from timeit import default_timer as timer
 +
 +start = timer()
 +# ...
 +end = timer()
 +print(end - start) # Time in seconds, e.g. 5.38091952400282
 +</code>
  
  
Ligne 446: Ligne 521:
 </code> </code>
  
 +Trouver toutes les occurrences qui correspondent à un motif ([[https://stackoverflow.com/questions/4697882/how-can-i-find-all-matches-to-a-regular-expression-in-python|source]]) :
 +<code python>
 +re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
 +# Output: ['cats', 'dogs']
 +</code>
  
  
 +=== Remplacer un motif ===
 +
 +<code python>
 +re.sub(r'[\x00-\x08\x0B-\x0C\x0E-\x1F]', '', content)
 +</code>
 +
 +
 +
 +
 +
 +==== Flottants ====
 +
 +=== Tronquer un flottant ===
 +
 +Utiliser la fonction ''round'':
 +<code python>
 +round(1.23456, 3) # 1.235
 +</code>
 +
 +
 +=== Tester si une chaîne est un flottant ===
 +
 +<code python>
 +s.replace('.','',1).isdigit()
 +</code>
 +
 +
 +=== Tester si un flottant est NaN ===
 +
 +<code python>
 +import math
 +
 +math.isnan(f)
 +</code>
  
  
Ligne 533: Ligne 647:
 <code python> <code python>
 bin(14) # '0b1110' bin(14) # '0b1110'
-</code> 
- 
- 
-=== Tronquer un flottant === 
- 
-Utiliser la fonction ''round'': 
-<code python> 
-round(1.23456, 3) # 1.235 
-</code> 
- 
- 
-=== Tester si une chaîne est un flottant === 
- 
-<code bash> 
-s.replace('.','',1).isdigit() 
 </code> </code>
  
Ligne 567: Ligne 666:
 import os import os
 redirected_to_file = not (os.fstat(0) == os.fstat(1)) redirected_to_file = not (os.fstat(0) == os.fstat(1))
 +</code>
 +
 +Une solution plus simple (et semble plus fonctionnelle), mais pas forcément valide avec Windows :
 +<code python>
 +import sys
 +
 +if sys.stdout.isatty():
 +    print "Not redirected"
 +else:
 +    sys.stderr.write("Redirected!\n")
 </code> </code>
  
Ligne 597: Ligne 706:
  
  
 +=== Connaître le nom du script exécuté ===
  
 +[[https://stackoverflow.com/questions/4152963/get-name-of-current-script-in-python|Source]]
  
- +<code python> 
 +import os 
 +os.path.basename(__file__) 
 +</code>
 ==== Dictionnaires ==== ==== Dictionnaires ====
  
Ligne 693: Ligne 806:
  
  
 +==== Débugguer un segfault ====
  
 +  * [[https://stackoverflow.com/questions/16731115/how-to-debug-a-python-segmentation-fault]]
 +  * https://docs.python.org/3/library/faulthandler.html
 +
 +<code bash>
 +export PYTHONFAULTHANDLER=1
 +</code>
  
  • python/accueil.1640426650.txt.gz
  • Dernière modification : 2021/12/25 11:04
  • de phsw