Écrire des fonctions en Python
Shayne Miel
Software Architect @ Duo Security
def copy(src, dst): """Copier le contenu d'un fichier dans un autre. Args: src (str): Nom du fichier à copier. dst (str): Emplacement du nouveau fichier. """# Ouvrir le fichier source et lire son contenu with open(src) as f_src: contents = f_src.read() # Ouvrir le fichier de destination et écrire le contenu with open(dst, 'w') as f_dst: f_dst.write(contents)
with open('my_file.txt') as my_file:
for line in my_file:
# faire quelque chose
def copy(src, dst): """Copier le contenu d'un fichier dans un autre. Args: src (str): Nom du fichier à copier. dst (str): Emplacement du nouveau fichier. """# Ouvrir les deux fichiers with open(src) as f_src: with open(dst, 'w') as f_dst:# Lire et écrire chaque ligne une à la fois for line in f_src: f_dst.write(line)
def get_printer(ip): p = connect_to_printer(ip) yield # DOIT être appelé sinon personne d'autre ne pourra # se connecter à l'imprimante p.disconnect() print('disconnected from printer')doc = {'text': 'This is my text.'} with get_printer('10.0.34.111') as printer: printer.print_page(doc['txt'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
printer.print_page(doc['txt'])
KeyError: 'txt'
try: # code pouvant lever une erreur except: # traiter l'erreurfinally: # ce code s'exécute dans tous les cas
def get_printer(ip): p = connect_to_printer(ip) try: yield finally: p.disconnect() print('disconnected from printer')doc = {'text': 'This is my text.'} with get_printer('10.0.34.111') as printer: printer.print_page(doc['txt'])
disconnected from printer
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
printer.print_page(doc['txt'])
KeyError: 'txt'
| Open | Close |
| Lock | Release |
| Change | Reset |
| Enter | Exit |
| Start | Stop |
| Setup | Teardown |
| Connect | Disconnect |
Écrire des fonctions en Python