.. _td2acorrectionsession2Crst: ==================================================== 2A.soft - IPython et commandes magiques - correction ==================================================== .. only:: html **Links:** :download:`notebook `, :downloadlink:`html `, :download:`python `, :downloadlink:`slides `, :githublink:`GitHub|_doc/notebooks/td2a/td2a_correction_session_2C.ipynb|*` Aperçu des `commandes magiques `__ pour automatiser un peu plus les tâches courantes. .. code:: ipython3 %matplotlib inline import matplotlib.pyplot as plt .. parsed-literal:: Populating the interactive namespace from numpy and matplotlib .. code:: ipython3 from jyquickhelper import add_notebook_menu add_notebook_menu() .. contents:: :local: Exercice 1 : votre propre magique commande ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ On implémente la commande ``%monplot`` qui prend un fichier texte, appelle la commande `plot `__ et stocke le résultat dans la variable ``df`` qui est ajoutée à l’espace de travail. .. code:: ipython3 from IPython.core.magic import Magics, magics_class, line_magic, cell_magic, line_cell_magic import pandas @magics_class class CustomMagics(Magics): @line_magic def monplot(self, line): df = pandas.read_csv(line, sep="\t") pl = df.plot() if self.shell is not None: self.shell.user_ns["df"] = df ip = get_ipython() ip.register_magics(CustomMagics) .. code:: ipython3 import pyensae.datasource pyensae.datasource.download_data("marathon.txt") .. parsed-literal:: downloading of http://www.xavierdupre.fr/enseignement/complements/marathon.txt to marathon.txt .. parsed-literal:: 'marathon.txt' .. code:: ipython3 %monplot marathon.txt .. image:: td2a_correction_session_2C_6_0.png Sans prétraitement, cela n’a pas toujours un sens. Mais cela devient pratique dès qu’il faut automatiser la création d’un rapport à partir de données qui se présentent toujours sous le même format. D’une manière générale, cela revient à réduire la syntaxe des tâches répétitives.