Python

De Octet.ca

Cet article contient de l'information particulière concernant python.

Optimisation[modifier]

pylint fichier.py

Pour suivre les standards de codage:

autopep8 -i fichier.py

Installer une librairie locale[modifier]

python setup.py install --home=LOCALDIR

Code pour faire un script[modifier]

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
 
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.

Name:        script.py
Description: Faire un appel d'un script python et lire les arguments

Notes: 

Author: Miguel Tremblay  / https://ptaff.ca/miguel/
Date: 26 avril 2024
"""

import sys

def main(input1, input2):
   """
   Fonction qui fait des choses...
   """
   print ("Des choses")

if __name__ == "__main__":

   if len(sys.argv) < 3:
       print ("Usage script.py input.txt output.txt")
       sys.exit(1)

   sInput1 = sys.argv[1]
   sInput2 = sys.argv[2]

   main(sInput1, sInput2)

Vérifier si un répertoire ou un fichier existe[modifier]

os.path.exists(path)


Fichier texte et liste[modifier]

Ouverture[modifier]

f = open('/tmp/workfile', 'w')
lListString = f.readlines()

Pour éviter les retour de ligne à la fin de chaque ligne utiliser:

lListString = f.read().striplines()

Écriture[modifier]

Comment écrire un fichier texte avec une liste en python. Il faut ajouter un '\n' à la main pour avoir le résultat souhaité.

f.writelines([sString+os.linesep for sString in lList])

Génération automatique de documentation html[modifier]

epydoc --html  --show-sourcecode  *.py

Utiliser epydoc. Voir la documentation pour la syntaxe.

Convertir un nombre dans un nombre fixe de lettres[modifier]

sRes ="%02d" % nNumber

Pour utiliser une variable pour le nombre de chiffres:

sRes = str(i).zfill(nNumberDigit)

Dates[modifier]

Convertir ISO 8601 en classe datetime[modifier]

datetime.datetime.strptime(string_iso8601, "%Y-%m-%dT%H:%M:%SZ")

Voir aussi[modifier]