# Fichier: python_cheats/cheatsheets/ipython.txt
# Cheatsheet IPython - Guide Complet pour Débutants


[OK] QU'EST-CE QU'IPYTHON ?

# IPython (Interactive Python) est un shell Python amélioré qui offre:
# [OK] Auto-complétion intelligente
# [OK] Coloration syntaxique
# [OK] Historique des commandes
# [OK] Commandes magiques
# [OK] Introspection des objets
# [OK] Débogage interactif
# [OK] Intégration avec Jupyter

# IPython vs Python standard:
python          # Shell Python basique
ipython         # Shell Python enrichi et interactif


[OK] INSTALLATION


# Installer IPython
pip install ipython

# Installer avec extras pour Jupyter
pip install ipython[notebook]
pip install ipython[all]

# Vérifier installation
ipython --version
ipython -V

# Installer dans environnement virtuel
python -m venv .venv
source .venv/bin/activate       # Linux/Mac
.venv\Scripts\activate          # Windows
pip install ipython


[OK] LANCER IPYTHON


# Démarrer IPython
ipython

# Démarrer avec profil spécifique
ipython --profile=myprofile

# Démarrer sans bannière
ipython --no-banner

# Démarrer sans configuration
ipython --no-confirm-exit

# Démarrer en mode classique (comme Python standard)
ipython --classic

# Démarrer et exécuter fichier
ipython script.py
ipython -i script.py            # Mode interactif après exécution

# Démarrer et exécuter commande
ipython -c "print('Hello')"

# Quitter IPython
exit                            # Commande
quit                            # Commande
Ctrl+D                          # Raccourci Linux/Mac
Ctrl+Z puis Enter               # Raccourci Windows


[OK] INTERFACE IPYTHON


# Prompt IPython
In [1]:                         # Entrée (numérotée)
Out[1]:                         # Sortie (numérotée)

# Exemple d'utilisation:
In [1]: 2 + 2
Out[1]: 4

In [2]: "Hello"
Out[2]: 'Hello'

In [3]: print("World")          # print() n'a pas de Out
World

# Continuation de ligne
In [4]: result = (
   ...:     1 + 2 +
   ...:     3 + 4
   ...: )

# Les trois points (...:) indiquent une continuation


[OK] AUTO-COMPLÉTION


# Appuyer sur TAB pour compléter

# Complétion de variables
In [1]: my_variable = "Hello"
In [2]: my_v<TAB>               # Complète en my_variable

# Complétion de méthodes
In [3]: my_variable.<TAB>       # Affiche toutes les méthodes disponibles
In [3]: my_variable.up<TAB>     # Complète en .upper()

# Complétion d'imports
In [4]: import os<TAB>          # Propose os, os.path, etc.
In [5]: from os import <TAB>    # Liste tout ce qui peut être importé

# Complétion de chemins
In [6]: open("./data/<TAB>")    # Affiche fichiers du dossier

# Complétion de dictionnaires
In [7]: data = {"name": "Alice", "age": 30}
In [8]: data["<TAB>"]           # Affiche 'name' et 'age'


[OK] AIDE ET INTROSPECTION


# === Obtenir de l'aide ===

# Aide rapide avec ?
In [1]: len?                    # Affiche docstring de len()
In [2]: str.upper?              # Affiche docstring de upper()
In [3]: my_variable?            # Affiche infos sur my_variable

# Aide détaillée avec ??
In [4]: len??                   # Affiche docstring + code source
In [5]: str.upper??             # Code source si disponible

# Aide générale
In [6]: ?                       # Introduction à IPython
In [7]: help()                  # Système d'aide Python

# Recherche dans les noms d'objets
In [8]: *Warning?               # Trouve tous les objets finissant par Warning
In [9]: str.*find*?             # Méthodes de str contenant 'find'

# === Introspection d'objets ===

# Type d'un objet
In [10]: type(my_variable)
Out[10]: str

# Lister attributs et méthodes
In [11]: dir(my_variable)       # Liste tous les attributs
In [12]: dir()                  # Liste objets dans namespace actuel

# Vérifier si attribut existe
In [13]: hasattr(my_variable, 'upper')
Out[13]: True

# Voir le code source
In [14]: import math
In [15]: ??math.sqrt            # Affiche le code (si Python)


[OK] HISTORIQUE DES COMMANDES


# === Navigation dans l'historique ===

# Flèche haut/bas
^                               # Commande précédente
v                               # Commande suivante

# Recherche dans l'historique
Ctrl+R                          # Recherche inversée
# Taper quelques lettres pour chercher

# === Variables spéciales d'historique ===

# _ : dernière sortie
In [1]: 2 + 2
Out[1]: 4

In [2]: _ + 10
Out[2]: 14                      # 4 + 10

# __ : avant-dernière sortie
In [3]: __
Out[3]: 4

# ___ : avant-avant-dernière sortie
In [4]: ___
Out[4]: 4

# _N : sortie spécifique (N = numéro)
In [5]: _1                      # Sortie de In [1]
Out[5]: 4

In [6]: _2
Out[6]: 14

# _iN : entrée spécifique
In [7]: _i1                     # Entrée de In [1]
Out[7]: '2 + 2'

# === Commandes d'historique ===

# Voir l'historique
In [8]: %history                # Tout l'historique
In [9]: %history -n 5           # 5 dernières commandes
In [10]: %history 1-5           # Commandes 1 à 5
In [11]: %history -g print      # Commandes contenant 'print'

# Sauvegarder historique
In [12]: %save script.py 1-5    # Sauvegarde commandes 1-5
In [13]: %save script.py 1 3 5  # Sauvegarde commandes 1, 3, 5

# Recharger historique
In [14]: %recall 3              # Rappelle commande 3 (éditable)
In [15]: %rerun 1-3             # Réexécute commandes 1-3

# Éditer historique
In [16]: %edit 5                # Ouvre commande 5 dans éditeur


[OK] COMMANDES MAGIQUES


# Les commandes magiques commencent par % (une ligne) ou %% (cellule)

# === Lister les commandes magiques ===

In [1]: %lsmagic                # Liste toutes les commandes magiques
In [2]: %magic                  # Documentation complète
In [3]: %quickref               # Référence rapide


# === COMMANDES MAGIQUES ESSENTIELLES ===


# --- Exécution de code ---

# %run : Exécuter un script Python
In [4]: %run script.py
In [5]: %run -i script.py       # Exécute dans namespace actuel
In [6]: %run -t script.py       # Avec temps d'exécution
In [7]: %run -d script.py       # Avec débogueur
In [8]: %run -p script.py       # Avec profiler

# %load : Charger code depuis fichier
In [9]: %load script.py         # Charge le code (ne l'exécute pas)
In [10]: %load http://example.com/code.py  # Depuis URL

# %edit : Éditer code dans éditeur externe
In [11]: %edit                  # Ouvre éditeur vide
In [12]: %edit script.py        # Édite fichier
In [13]: %edit 5                # Édite commande 5

# --- Temps et performance ---

# %time : Temps d'exécution (une fois)
In [14]: %time sum(range(1000000))
CPU times: user 25.3 ms, sys: 1.2 ms, total: 26.5 ms
Wall time: 26.8 ms
Out[14]: 499999500000

# %timeit : Temps moyen (plusieurs exécutions)
In [15]: %timeit sum(range(1000))
10000 loops, best of 5: 24.3 µs per loop

In [16]: %timeit -n 100 -r 5 sum(range(1000))
# -n 100 : 100 exécutions par boucle
# -r 5 : 5 répétitions

# %%timeit : Pour cellule entière
In [17]: %%timeit
    ...: x = 0
    ...: for i in range(1000):
    ...:     x += i
885 µs ± 12.3 µs per loop

# --- Variables et namespace ---

# %who : Lister variables (format simple)
In [18]: x = 5
In [19]: name = "Alice"
In [20]: %who
name    x

# %who_ls : Lister variables (format liste Python)
In [21]: %who_ls
Out[21]: ['name', 'x']

# %whos : Détails des variables (type, taille, contenu)
In [22]: %whos
Variable   Type    Data/Info
-----------------------------
name       str     Alice
x          int     5

# %who [type] : Filtrer par type
In [23]: %who str               # Seulement les strings
name

# %reset : Supprimer variables
In [24]: %reset                 # Demande confirmation
In [25]: %reset -f              # Force sans confirmation
In [26]: %reset_selective x     # Supprime seulement x
In [27]: %reset_selective -f "^te"  # Supprime variables commençant par 'te'

# %xdel : Supprimer variable et références
In [28]: %xdel variable_name

# --- Fichiers et système ---

# %pwd : Afficher dossier actuel
In [29]: %pwd
Out[29]: '/home/user/project'

# %cd : Changer de dossier
In [30]: %cd /home/user/data
In [31]: %cd ..                 # Dossier parent
In [32]: %cd -                  # Dossier précédent

# %ls : Lister fichiers
In [33]: %ls
In [34]: %ls -l                 # Format long
In [35]: %ls *.py               # Fichiers .py seulement

# %mkdir : Créer dossier
In [36]: %mkdir new_folder

# %rmdir : Supprimer dossier vide
In [37]: %rmdir old_folder

# %cp : Copier fichier
In [38]: %cp file1.txt file2.txt

# %mv : Déplacer/renommer
In [39]: %mv old_name.txt new_name.txt

# %rm : Supprimer fichier
In [40]: %rm file.txt

# %cat : Afficher contenu fichier
In [41]: %cat script.py

# --- Historique ---

# %history : Voir historique (détaillé plus haut)
In [42]: %history -n 10

# %recall : Rappeler commande
In [43]: %recall 5

# %rerun : Réexécuter commandes
In [44]: %rerun 1-5

# %save : Sauvegarder commandes
In [45]: %save script.py 1-10

# %macro : Créer macro depuis historique
In [46]: %macro my_macro 1-3    # my_macro exécutera commandes 1-3
In [47]: my_macro               # Exécute la macro

# --- Débogage ---

# %debug : Lancer débogueur après erreur
In [48]: 1 / 0
---------------------------------------------------------------------------
ZeroDivisionError: division by zero

In [49]: %debug                 # Lance pdb sur l'erreur
> <ipython-input-48>(1)<module>()
ipdb>

# %pdb : Activer débogueur automatique
In [50]: %pdb                   # Active/désactive
In [51]: %pdb on                # Active
In [52]: %pdb off               # Désactive

# %prun : Profiler code
In [53]: %prun sum(range(100000))  # Affiche rapport de performance

# --- Système ---

# ! : Exécuter commande shell
In [54]: !ls                    # Commande shell
In [55]: !pwd
In [56]: !echo "Hello"
In [57]: !git status

# Capturer sortie shell
In [58]: files = !ls *.py
In [59]: print(files)
['script.py', 'test.py']

# Utiliser variable Python dans shell
In [60]: filename = "data.txt"
In [61]: !cat $filename         # $filename devient data.txt

# %system : Alias pour !
In [62]: %system ls

# %sx : Comme ! mais retourne liste
In [63]: result = %sx ls

# --- Alias ---

# %alias : Créer alias de commande
In [64]: %alias ll ls -la
In [65]: ll                     # Exécute ls -la

# %unalias : Supprimer alias
In [66]: %unalias ll

# --- Configuration ---

# %config : Voir/modifier configuration
In [67]: %config                # Affiche toute la config
In [68]: %config IPCompleter    # Config de l'auto-complétion

# %colors : Changer schéma de couleurs
In [69]: %colors Linux          # Fond noir
In [70]: %colors LightBG        # Fond clair
In [71]: %colors NoColor        # Pas de couleurs

# %automagic : Activer/désactiver automagic
In [72]: %automagic             # Toggle
# Avec automagic, pas besoin de % devant les commandes
In [73]: cd /home               # Marche sans %
In [74]: pwd                    # Marche sans %

# --- Clipboard ---

# %paste : Coller code depuis clipboard
In [75]: %paste                 # Colle et exécute
# Utile pour code avec indentation

# %cpaste : Coller code interactivement
In [76]: %cpaste
Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
:def hello():
:    print("Hello")
:--

# --- Environnement ---

# %env : Variables d'environnement
In [77]: %env                   # Affiche toutes les variables
In [78]: %env PATH              # Affiche PATH
In [79]: %env MY_VAR=value      # Définit variable

# %pip : Installer packages
In [80]: %pip install requests
In [81]: %pip list
In [82]: %pip show numpy

# %conda : Commandes conda
In [83]: %conda install numpy
In [84]: %conda list

# --- Notebook (si Jupyter) ---

# %%html : Afficher HTML
In [85]: %%html
    ...: <h1>Titre</h1>
    ...: <p>Paragraphe</p>

# %%javascript : Exécuter JavaScript
In [86]: %%javascript
    ...: console.log("Hello from JS");

# %%latex : Afficher LaTeX
In [87]: %%latex
    ...: \begin{equation}
    ...: E = mc^2
    ...: \end{equation}

# %%markdown : Afficher Markdown
In [88]: %%markdown
    ...: # Titre
    ...: **Gras** et *italique*

# --- Autres commandes utiles ---

# %logstart : Enregistrer session
In [89]: %logstart mylog.py     # Enregistre dans fichier

# %logstop : Arrêter enregistrement
In [90]: %logstop

# %notebook : Exporter en notebook
In [91]: %notebook -e output.ipynb  # Exporte session

# %pycat : Afficher fichier Python coloré
In [92]: %pycat script.py

# %page : Afficher avec paginateur
In [93]: %page long_text

# %precision : Précision des floats
In [94]: %precision 2           # 2 décimales
In [95]: 1/3
Out[95]: 0.33

# %psearch : Rechercher objets
In [96]: %psearch os.*dir*      # Objets de os contenant 'dir'

# %bookmark : Marque-pages de dossiers
In [97]: %bookmark data /path/to/data
In [98]: %cd -b data            # Va au bookmark

# %dhist : Historique des dossiers
In [99]: %dhist

# %killbgscripts : Tuer scripts background
In [100]: %killbgscripts


[OK] COMMANDES MAGIQUES CELLULE (Jupyter/IPython Notebook)


# Les commandes %% s'appliquent à toute la cellule

# %%writefile : Écrire dans fichier
In [1]: %%writefile script.py
   ...: def hello():
   ...:     print("Hello, World!")
   ...:
   ...: hello()

# %%bash : Exécuter bash
In [2]: %%bash
   ...: echo "Hello from Bash"
   ...: pwd
   ...: ls -la

# %%python : Exécuter Python (dans sous-processus)
In [3]: %%python
   ...: print("Hello")

# %%python2 : Exécuter avec Python 2
In [4]: %%python2
   ...: print "Hello from Python 2"

# %%python3 : Exécuter avec Python 3
In [5]: %%python3
   ...: print("Hello from Python 3")

# %%ruby : Exécuter Ruby
In [6]: %%ruby
   ...: puts "Hello from Ruby"

# %%perl : Exécuter Perl
In [7]: %%perl
   ...: print "Hello from Perl\n";

# %%sh : Exécuter shell
In [8]: %%sh
   ...: echo "Shell command"

# %%capture : Capturer sortie
In [9]: %%capture output
   ...: print("This is captured")
   ...: print("Not displayed")

In [10]: print(output.stdout)   # Affiche sortie capturée

# %%time : Timer pour cellule
In [11]: %%time
    ...: sum(range(1000000))

# %%timeit : Benchmark cellule
In [12]: %%timeit
    ...: x = 0
    ...: for i in range(1000):
    ...:     x += i

# %%prun : Profiler cellule
In [13]: %%prun
    ...: sum(range(100000))

# %%debug : Déboguer cellule
In [14]: %%debug
    ...: x = 1 / 0


[OK] RACCOURCIS CLAVIER


# === Navigation et édition ===

Ctrl+A              # Début de ligne
Ctrl+E              # Fin de ligne
Ctrl+B              # Caractère précédent (<-)
Ctrl+F              # Caractère suivant (->)
Alt+B               # Mot précédent
Alt+F               # Mot suivant

Ctrl+K              # Couper jusqu'à fin de ligne
Ctrl+U              # Couper jusqu'à début de ligne
Ctrl+Y              # Coller texte coupé
Alt+D               # Couper mot suivant
Ctrl+W              # Couper mot précédent

Ctrl+L              # Effacer écran
Ctrl+C              # Interrompre commande
Ctrl+D              # Quitter (ou EOF)
Ctrl+Z              # Suspendre (Linux/Mac)

# === Historique ===

^                   # Commande précédente
v                   # Commande suivante
Ctrl+R              # Recherche inversée dans historique
Ctrl+P              # Comme ^
Ctrl+N              # Comme v

# === Auto-complétion ===

Tab                 # Auto-complétion
Shift+Tab           # Afficher tooltip (Jupyter)

# === Aide ===

?                   # Après objet: afficher aide
??                  # Après objet: afficher code source


[OK] CONFIGURATION IPYTHON


# === Fichiers de configuration ===

# Localiser config
In [1]: %locate profile

# Créer profil par défaut
ipython profile create

# Créer profil personnalisé
ipython profile create myprofile

# Emplacement des profils:
# Linux/Mac: ~/.ipython/profile_default/
# Windows: %USERPROFILE%\.ipython\profile_default\

# Fichiers importants:
# ipython_config.py         # Configuration principale
# ipython_kernel_config.py  # Configuration kernel Jupyter
# startup/                  # Scripts exécutés au démarrage


# === Fichier ipython_config.py ===

# Exemple de configuration
c = get_config()

# Auto-complétion
c.InteractiveShell.automagic = True
c.IPCompleter.greedy = True             # Complétion agressive
c.IPCompleter.use_jedi = True           # Utiliser Jedi

# Historique
c.HistoryManager.hist_file = ':memory:' # Historique en mémoire
c.InteractiveShell.history_length = 10000

# Affichage
c.InteractiveShell.colors = 'Linux'     # Schéma de couleurs
c.InteractiveShell.confirm_exit = False # Pas de confirmation sortie
c.InteractiveShell.display_page = True  # Utiliser paginateur

# Auto-reload modules
c.InteractiveShellApp.exec_lines = [
    'import numpy as np',
    'import pandas as pd',
    '%load_ext autoreload',
    '%autoreload 2'
]

# Extensions
c.InteractiveShellApp.extensions = [
    'autoreload',
    'line_profiler',
]

# Logging
c.InteractiveShell.logstart = True
c.InteractiveShell.logfile = 'ipython_log.py'


# === Scripts de démarrage ===

# Créer script: ~/.ipython/profile_default/startup/00-first.py

# 00-first.py
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

print("Modules chargés automatiquement:")
print("- numpy as np")
print("- pandas as pd")
print("- matplotlib.pyplot as plt")

# Les scripts dans startup/ sont exécutés par ordre alphabétique
# 00-first.py sera exécuté en premier


[OK] EXTENSIONS IPYTHON


# === Installer extensions ===

pip install ipython-extensions

# === Charger extension ===

In [1]: %load_ext extension_name

# === Extensions populaires ===

# --- autoreload : Recharge modules automatiquement ---
In [2]: %load_ext autoreload
In [3]: %autoreload 2           # Recharge tous les modules
In [4]: %autoreload 1           # Recharge modules spécifiés
In [5]: %aimport module_name    # Spécifier module à recharger

# Modes autoreload:
# 0 : Désactivé
# 1 : Recharge modules importés avec %aimport
# 2 : Recharge tous les modules (sauf exclus)

# --- line_profiler : Profiler ligne par ligne ---
pip install line_profiler

In [6]: %load_ext line_profiler
In [7]: %lprun -f function_name function_name(args)

# Exemple:
def slow_function():
    total = 0
    for i in range(1000):
        total += i
    return total

In [8]: %lprun -f slow_function slow_function()

# --- memory_profiler : Profiler mémoire ---
pip install memory_profiler

In [9]: %load_ext memory_profiler
In [10]: %memit sum(range(1000000))
peak memory: 52.34 MiB, increment: 0.12 MiB

In [11]: %mprun -f function_name function_name()

# --- sql : Requêtes SQL ---
pip install ipython-sql

In [12]: %load_ext sql
In [13]: %sql sqlite:///database.db
In [14]: %%sql
    ...: SELECT * FROM users LIMIT 10;

# --- rpy2 : Intégration R ---
pip install rpy2

In [15]: %load_ext rpy2.ipython
In [16]: %%R
    ...: x <- c(1, 2, 3, 4, 5)
    ...: mean(x)

# --- cython : Compiler code Cython ---
pip install cython

In [17]: %load_ext cython
In [18]: %%cython
    ...: def fast_function(int n):
    ...:     cdef int i, total = 0
    ...:     for i in range(n):
    ...:         total += i
    ...:     return total

# --- version_information : Infos versions ---
pip install version_information

In [19]: %load_ext version_information
In [20]: %version_information numpy, pandas, matplotlib

# === Décharger extension ===

In [21]: %unload_ext extension_name

# === Lister extensions chargées ===

In [22]: %lsmagic                # Affiche aussi les extensions


[OK] ASTUCES ET WORKFLOWS


# === Import automatique modules courants ===

# Dans ipython_config.py ou script startup:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pathlib import Path

# === Afficher toutes les variables ===

In [1]: %who                     # Noms uniquement
In [2]: %whos                    # Avec détails
In [3]: dir()                    # Liste Python standard

# === Nettoyer namespace ===

In [4]: %reset -f                # Supprimer toutes les variables
In [5]: %reset_selective -f "^x" # Supprimer variables commençant par x

# === Mesurer performance ===

# Une ligne:
In [6]: %timeit [x**2 for x in range(1000)]

# Plusieurs lignes:
In [7]: %%timeit
   ...: result = []
   ...: for x in range(1000):
   ...:     result.append(x**2)

# Avec time pour une seule exécution:
In [8]: %time sum(range(1000000))

# === Déboguer erreur ===

In [9]: def buggy():
   ...:     x = 1
   ...:     y = 0
   ...:     return x / y

In [10]: buggy()                 # Génère erreur

In [11]: %debug                  # Lance débogueur sur dernière erreur
# Commandes débogueur:
# n : next (ligne suivante)
# s : step (entre dans fonction)
# c : continue
# q : quit
# p variable : print variable
# l : list code
# h : help

# === Déboguer automatiquement ===

In [12]: %pdb on                 # Active débogueur auto
In [13]: buggy()                 # Débogueur se lance automatiquement

# === Sauvegarder travail ===

# Sauvegarder historique:
In [14]: %save my_work.py 1-20   # Commandes 1 à 20

# Sauvegarder dans notebook:
In [15]: %notebook my_work.ipynb

# === Exécuter script avec variables ===

# script.py utilise variable 'data'
In [16]: data = [1, 2, 3, 4, 5]
In [17]: %run -i script.py       # -i : utilise namespace actuel

# === Éditer et réexécuter ===

In [18]: %edit 5                 # Édite commande 5
# Sauvegarde et ferme éditeur pour exécuter

# === Macros ===

# Créer macro depuis historique:
In [19]: %macro my_macro 1-5     # Commandes 1-5 deviennent macro

In [20]: my_macro                # Exécute la macro

# Sauvegarder macro:
In [21]: %store my_macro

# Charger macro:
In [22]: %store -r my_macro

# === Bookmarks de dossiers ===

In [23]: %bookmark data /path/to/data/folder
In [24]: %cd -b data             # Va au bookmark
In [25]: %bookmark -l            # Liste bookmarks
In [26]: %bookmark -d data       # Supprime bookmark

# === Intégration shell ===

# Capturer sortie:
In [27]: files = !ls *.py
In [28]: for f in files:
    ...:     print(f)

# Utiliser variables Python:
In [29]: name = "test.txt"
In [30]: !cat $name

# === Exécuter en background ===

In [31]: import time
In [32]: def long_task():
    ...:     time.sleep(10)
    ...:     print("Done!")

In [33]: %run -b long_task.py    # -b : background

# === Rich output (Jupyter) ===

from IPython.display import display, Image, HTML, Markdown

In [34]: display(HTML("<h1>Titre</h1>"))
In [35]: display(Image("image.png"))
In [36]: display(Markdown("**Gras** et *italique*"))


[OK] IPYTHON AVEC JUPYTER NOTEBOOK


# === Installer Jupyter ===

pip install jupyter
pip install jupyterlab           # Version moderne

# === Lancer Jupyter ===

jupyter notebook                 # Classic Notebook
jupyter lab                      # JupyterLab
jupyter notebook --port=8889     # Port spécifique
jupyter notebook --no-browser    # Sans ouvrir navigateur

# === Raccourcis Jupyter ===

# Mode Commande (Esc)
Enter           # Passer en mode Édition
A               # Insérer cellule au-dessus
B               # Insérer cellule en-dessous
D, D            # Supprimer cellule
Z               # Annuler suppression
M               # Convertir en Markdown
Y               # Convertir en Code
Shift+^/v       # Sélection multiple
Shift+M         # Fusionner cellules
Ctrl+S          # Sauvegarder
H               # Afficher aide raccourcis

# Mode Édition (Enter)
Esc             # Passer en mode Commande
Ctrl+Enter      # Exécuter cellule
Shift+Enter     # Exécuter et aller à la suivante
Alt+Enter       # Exécuter et insérer nouvelle cellule
Ctrl+/          # Commenter/décommenter
Tab             # Auto-complétion
Shift+Tab       # Afficher tooltip/aide


[OK] LISTE COMPLÈTE DES COMMANDES MAGIQUES


# === COMMANDES MAGIQUES GLOBALES ===

# %lsmagic : Lister toutes les commandes magiques
In [1]: %lsmagic
Available line magics:
%alias  %automagic  %bookmark  %cd  %colors  %config  ...
Available cell magics:
%%bash  %%html  %%javascript  %%latex  %%markdown  ...

# %quickref : Référence rapide IPython
In [2]: %quickref               # Affiche guide de référence rapide

# %magic : Documentation complète sur magic commands
In [3]: %magic                  # Guide détaillé des commandes magiques

# %history : Historique des commandes
In [4]: %history                # Tout l'historique
In [5]: %history -n 10          # 10 dernières commandes
In [6]: %history 1-5            # Commandes 1 à 5
In [7]: %history -g "import"    # Recherche "import"
In [8]: %history -p             # Avec numéros de prompt
In [9]: %history -o             # Seulement les sorties
In [10]: %history -f file.py    # Sauvegarder dans fichier

# %recall : Récupérer commande passée
In [11]: %recall 5              # Rappelle commande 5 (éditable)
In [12]: %recall -g "def"       # Première commande contenant "def"

# %pastebin : Envoyer code vers pastebin
In [13]: %pastebin 1-10         # Envoie commandes 1-10
In [14]: %pastebin script.py    # Envoie fichier
# Retourne URL du pastebin

# %rehashx : Recharger commandes système
In [15]: %rehashx               # Recharge PATH et commandes shell

# %reset : Réinitialiser namespace
In [16]: %reset                 # Demande confirmation
In [17]: %reset -f              # Force sans confirmation
In [18]: %reset -s              # Reset + supprime historique

# %reset_selective : Réinitialisation partielle
In [19]: %reset_selective x y   # Supprime seulement x et y
In [20]: %reset_selective -f "^temp"  # Supprime variables commençant par temp


# === EXÉCUTION DE CODE / FICHIERS ===

# %run : Exécuter fichier Python
In [21]: %run script.py
In [22]: %run -i script.py      # Dans namespace actuel
In [23]: %run -t script.py      # Avec timer
In [24]: %run -d script.py      # Avec débogueur
In [25]: %run -p script.py      # Avec profiler
In [26]: %run -n module         # Exécute module (python -m)
In [27]: %run -m module         # Importe et exécute module

# %load : Charger code dans cellule
In [28]: %load script.py        # Charge fichier
In [29]: %load http://example.com/code.py  # Depuis URL
In [30]: %load -s 10-20 script.py  # Lignes 10 à 20 seulement
In [31]: %load -y script.py     # Sans confirmation

# %load_ext : Charger extension
In [32]: %load_ext autoreload
In [33]: %load_ext line_profiler
In [34]: %load_ext memory_profiler
In [35]: %load_ext sql

# %unload_ext : Décharger extension
In [36]: %unload_ext autoreload

# %reload_ext : Recharger extension
In [37]: %reload_ext autoreload

# %pycat : Afficher fichier avec coloration syntaxique
In [38]: %pycat script.py       # Affiche avec couleurs


# === PROFILING & PERFORMANCE ===

# %time : Temps d'exécution (une fois)
In [39]: %time sum(range(1000000))
CPU times: user 28.5 ms, sys: 2.1 ms, total: 30.6 ms
Wall time: 30.8 ms

# %timeit : Mesure précise (plusieurs exécutions)
In [40]: %timeit sum(range(1000))
25.3 µs ± 1.2 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [41]: %timeit -n 1000 -r 7 sum(range(1000))
# -n : nombre de boucles par exécution
# -r : nombre de répétitions

In [42]: %timeit -o result = sum(range(1000))  # -o : retourne objet TimeitResult

# %%time : Temps pour cellule complète
In [43]: %%time
    ...: x = 0
    ...: for i in range(1000000):
    ...:     x += i

# %%timeit : Benchmark cellule complète
In [44]: %%timeit
    ...: x = 0
    ...: for i in range(1000):
    ...:     x += i

In [45]: %%timeit -n 10 -r 5
    ...: result = []
    ...: for i in range(100):
    ...:     result.append(i**2)

# %prun : Profiler code (cProfile)
In [46]: %prun sum(range(100000))
# Affiche temps par fonction

In [47]: %prun -s cumulative sum(range(100000))  # Tri par temps cumulatif
In [48]: %prun -l 10 sum(range(100000))  # Top 10 fonctions
In [49]: %prun -D profile.txt sum(range(100000))  # Sauvegarder résultats

# %%prun : Profiler cellule
In [50]: %%prun
    ...: def slow():
    ...:     return sum(range(100000))
    ...: slow()

# %lprun : Profiler ligne par ligne (nécessite line_profiler)
# Installer: pip install line_profiler
In [51]: %load_ext line_profiler
In [52]: def my_func():
    ...:     total = 0
    ...:     for i in range(1000):
    ...:         total += i
    ...:     return total

In [53]: %lprun -f my_func my_func()
# -f : fonction à profiler

# %mprun : Profiler mémoire ligne par ligne (nécessite memory_profiler)
# Installer: pip install memory_profiler
In [54]: %load_ext memory_profiler
In [55]: %mprun -f my_func my_func()

# %memit : Mesurer mémoire consommée
In [56]: %memit sum(range(1000000))
peak memory: 52.45 MiB, increment: 0.15 MiB

In [57]: %%memit
    ...: x = [i**2 for i in range(100000)]


# === DEBUGGING ===

# %pdb : Activer/désactiver débogueur automatique
In [58]: %pdb                   # Toggle on/off
In [59]: %pdb on                # Activer
In [60]: %pdb off               # Désactiver
# Quand activé, pdb démarre automatiquement en cas d'erreur

# %debug : Lancer débogueur après erreur
In [61]: 1 / 0                  # Génère erreur
In [62]: %debug                 # Lance pdb sur dernière erreur

# Commandes dans pdb:
# h, help      : aide
# w, where     : stack trace
# u, up        : monter dans la pile
# d, down      : descendre dans la pile
# n, next      : ligne suivante
# s, step      : entrer dans fonction
# c, continue  : continuer exécution
# r, return    : jusqu'à return
# p, print     : afficher variable
# pp           : pretty print
# l, list      : afficher code
# a, args      : arguments de fonction
# b, break     : ajouter breakpoint
# cl, clear    : supprimer breakpoint
# q, quit      : quitter

# %xmode : Contrôler verbosité des erreurs
In [63]: %xmode Plain           # Minimal
In [64]: %xmode Context         # Avec contexte (défaut)
In [65]: %xmode Verbose         # Maximum de détails

# %tb : Afficher dernier traceback
In [66]: %tb                    # Affiche dernière erreur


# === VARIABLES / OBJETS ===

# %who : Lister variables (format simple)
In [67]: %who                   # Toutes les variables
In [68]: %who str               # Seulement les strings
In [69]: %who int float         # Seulement int et float
In [70]: %who function          # Seulement les fonctions

# %whos : Liste détaillée des variables
In [71]: %whos
Variable   Type       Data/Info
--------------------------------
x          int        42
name       str        Alice
data       list       n=5

# %who_ls : Liste format Python
In [72]: %who_ls                # Retourne liste Python
Out[72]: ['data', 'name', 'x']

In [73]: vars = %who_ls
In [74]: print(vars)

# %reset : Supprimer variables (voir section GLOBALES)

# %xdel : Supprimer variable et toutes références
In [75]: x = [1, 2, 3]
In [76]: y = x                  # y référence x
In [77]: %xdel x                # Supprime x et casse référence de y

# %store : Sauvegarder variable entre sessions
In [78]: important_data = [1, 2, 3, 4, 5]
In [79]: %store important_data  # Sauvegarde

# Nouvelle session IPython:
In [1]: %store -r important_data  # Restaure
In [2]: print(important_data)
[1, 2, 3, 4, 5]

In [80]: %store -d important_data  # Supprimer du store
In [81]: %store -z              # Supprimer tout le store
In [82]: %store                 # Lister variables stockées


# === SYSTEM & OS ===

# %pwd : Afficher dossier courant
In [83]: %pwd
Out[83]: '/home/user/project'

# %ls : Lister fichiers
In [84]: %ls                    # Liste simple
In [85]: %ls -l                 # Format long
In [86]: %ls -a                 # Inclut fichiers cachés
In [87]: %ls *.py               # Filtrer par pattern
In [88]: %ls -d data/           # Infos sur dossier

# %cd : Changer de dossier
In [89]: %cd /home/user/data
In [90]: %cd ..                 # Dossier parent
In [91]: %cd ~                  # Home directory
In [92]: %cd -                  # Dossier précédent
In [93]: %cd -b bookmark_name   # Aller à bookmark

# %pushd / %popd : Stack de dossiers
In [94]: %pushd /path/to/dir1   # Empile et change
In [95]: %pushd /path/to/dir2   # Empile et change
In [96]: %dirs                  # Affiche stack
In [97]: %popd                  # Dépile et retourne

# %dhist : Historique des dossiers visités
In [98]: %dhist
Directory history (kept in _dh)
0: /home/user/project
1: /home/user/data
2: /home/user/project/src

# %env : Variables d'environnement
In [99]: %env                   # Toutes les variables
In [100]: %env PATH             # Variable spécifique
In [101]: %env MY_VAR=value     # Définir variable
In [102]: %env MY_VAR=$PATH:/new/path  # Utiliser autre variable

# %set_env : Alias pour %env (définir)
In [103]: %set_env DEBUG=1

# %mkdir : Créer dossier
In [104]: %mkdir new_folder
In [105]: %mkdir -p path/to/new/folder  # Créer parents

# %rmdir : Supprimer dossier vide
In [106]: %rmdir old_folder

# %cp : Copier fichier/dossier
In [107]: %cp file1.txt file2.txt
In [108]: %cp -r folder1 folder2  # Récursif

# %mv : Déplacer/renommer
In [109]: %mv old_name.txt new_name.txt
In [110]: %mv file.txt folder/

# %rm : Supprimer fichier
In [111]: %rm file.txt
In [112]: %rm -r folder         # Récursif
In [113]: %rm -f file.txt       # Force

# %cat : Afficher contenu fichier
In [114]: %cat script.py
In [115]: %cat file1.txt file2.txt  # Plusieurs fichiers

# %less : Afficher avec paginateur
In [116]: %less large_file.txt

# %more : Afficher avec paginateur (alias)
In [117]: %more large_file.txt

# %man : Afficher page man (Linux/Mac)
In [118]: %man ls


# === SHELL / COMMANDES SYSTÈME ===

# ! : Exécuter commande shell
In [119]: !ls
In [120]: !pwd
In [121]: !git status
In [122]: !python --version

# Capturer sortie
In [123]: files = !ls *.py
In [124]: print(files)          # Liste de strings
['script.py', 'test.py', 'main.py']

# Utiliser variable Python dans shell
In [125]: filename = "data.txt"
In [126]: !cat $filename
In [127]: !wc -l $filename

# Boucle avec shell
In [128]: for f in !ls *.py:
     ...:     print(f)

# %system : Alias pour !
In [129]: %system ls

# %sx : Exécuter et retourner sortie
In [130]: result = %sx ls -la
In [131]: print(result)         # Liste de lignes

# %alias : Créer alias
In [132]: %alias ll ls -la
In [133]: ll                    # Exécute ls -la

In [134]: %alias mygrep grep -i --color
In [135]: mygrep "pattern" file.txt

# Lister alias
In [136]: %alias                # Affiche tous les alias

# %unalias : Supprimer alias
In [137]: %unalias ll

# %rehashx : Recharger commandes PATH
In [138]: %rehashx              # Actualise commandes disponibles


# === HISTORIQUE AVANCÉ ===

# %save : Sauvegarder commandes dans fichier
In [139]: %save script.py 1-10
In [140]: %save script.py 1 3 5  # Commandes spécifiques
In [141]: %save -a script.py 11-15  # Append
In [142]: %save -f script.py 1-10   # Force overwrite

# %macro : Créer macro depuis historique
In [143]: %macro my_macro 1-5
In [144]: my_macro              # Exécute commandes 1-5

In [145]: %macro process_data 10 15 20  # Commandes spécifiques

# Sauvegarder macro
In [146]: %store my_macro

# %rerun : Réexécuter commandes
In [147]: %rerun 5              # Réexécute commande 5
In [148]: %rerun 1-5            # Réexécute 1 à 5
In [149]: %rerun -l 3           # 3 dernières commandes

# %edit : Éditer dans éditeur externe
In [150]: %edit                 # Éditeur vide
In [151]: %edit script.py       # Édite fichier
In [152]: %edit 5               # Édite commande 5
In [153]: %edit 1-10            # Édite commandes 1-10
In [154]: %edit -p              # Édite commande précédente
In [155]: %edit -x              # N'exécute pas après édition

# Éditeur utilisé défini par $EDITOR


# === LOGGING / ENREGISTREMENT ===

# %logstart : Démarrer enregistrement session
In [156]: %logstart             # Fichier ipython_log.py
In [157]: %logstart mylog.py    # Fichier personnalisé
In [158]: %logstart -o mylog.py # Overwrite
In [159]: %logstart -r mylog.py # Rotate (nouveau si existe)
In [160]: %logstart -a mylog.py # Append
In [161]: %logstart -t mylog.py # Timestamp

# %logstate : État du logging
In [162]: %logstate
Logging is currently OFF

# %logstop : Arrêter logging
In [163]: %logstop

# %logon : Réactiver logging (si logstart déjà appelé)
In [164]: %logon

# %logoff : Désactiver temporairement
In [165]: %logoff


# === AFFICHAGE / FORMATAGE ===

# %colors : Changer schéma de couleurs
In [166]: %colors Linux         # Fond noir
In [167]: %colors LightBG       # Fond clair
In [168]: %colors NoColor       # Sans couleurs
In [169]: %colors Neutral       # Neutre

# %precision : Précision des floats
In [170]: %precision            # Affiche précision actuelle
In [171]: %precision 2          # 2 décimales
In [172]: %precision 5          # 5 décimales

In [173]: 1/3
Out[173]: 0.33

In [174]: %precision 10
In [175]: 1/3
Out[175]: 0.3333333333

# %pprint : Pretty printing on/off
In [176]: %pprint               # Toggle
In [177]: %pprint on            # Activer
In [178]: %pprint off           # Désactiver

# %page : Afficher avec paginateur
In [179]: %page long_variable
In [180]: %page some_object

# %pinfo : Infos sur objet (alias de ?)
In [181]: %pinfo len
In [182]: %pinfo str.upper

# %pinfo2 : Infos détaillées (alias de ??)
In [183]: %pinfo2 len

# %pdoc : Afficher docstring
In [184]: %pdoc str.upper

# %pdef : Afficher définition
In [185]: %pdef my_function

# %psource : Afficher code source
In [186]: %psource my_function

# %pfile : Afficher fichier entier de l'objet
In [187]: %pfile my_function


# === RECHERCHE ===

# %psearch : Rechercher objets par pattern
In [188]: %psearch os.*dir*     # Objets de os contenant 'dir'
In [189]: %psearch str.*find*   # Méthodes de str contenant 'find'
In [190]: %psearch -a *Error    # Tous objets finissant par Error
In [191]: %psearch -e os.*      # Pattern exact

# %who + pattern : Recherche dans variables
In [192]: %who str              # Variables de type str
In [193]: %who function         # Fonctions


# === BOOKMARKS ===

# %bookmark : Marque-page de dossiers
In [194]: %bookmark data /path/to/data
In [195]: %bookmark project ~/projects/myproject

# Aller à bookmark
In [196]: %cd -b data

# Lister bookmarks
In [197]: %bookmark -l
Current bookmarks:
data    -> /path/to/data
project -> /home/user/projects/myproject

# Supprimer bookmark
In [198]: %bookmark -d data

# %dhist : Historique dossiers (déjà vu)


# === CONFIGURATION ===

# %config : Voir/modifier configuration
In [199]: %config               # Toute la config
In [200]: %config IPCompleter   # Config auto-complétion
In [201]: %config TerminalInteractiveShell

# Modifier config
In [202]: %config IPCompleter.greedy = True
In [203]: %config TerminalInteractiveShell.editing_mode = 'vi'

# %automagic : Activer/désactiver automagic
In [204]: %automagic            # Toggle
# Avec automagic on, pas besoin de % devant commandes
In [205]: cd /home              # Marche sans %
In [206]: pwd                   # Marche sans %

# Automagic off:
In [207]: %automagic off
In [208]: %cd /home             # Besoin de % maintenant


# === CLIPBOARD ===

# %paste : Coller depuis clipboard et exécuter
In [209]: %paste
## Colle code et l'exécute immédiatement

# %cpaste : Coller interactivement
In [210]: %cpaste
Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
:def hello():
:    print("Hello, World!")
:--
# Code est exécuté

# %pastebin : Envoyer code vers pastebin (déjà vu)


# === PACKAGES / MODULES ===

# %pip : Commandes pip
In [211]: %pip install requests
In [212]: %pip install numpy pandas
In [213]: %pip install -U pip
In [214]: %pip list
In [215]: %pip show numpy
In [216]: %pip uninstall requests

# %conda : Commandes conda
In [217]: %conda install numpy
In [218]: %conda list
In [219]: %conda update numpy
In [220]: %conda info

# %aimport : Auto-import pour autoreload
# (Utilisé avec extension autoreload)
In [221]: %load_ext autoreload
In [222]: %autoreload 1
In [223]: %aimport my_module    # Recharge automatiquement


# === MATPLOTLIB ===

# %matplotlib : Backend matplotlib
In [224]: %matplotlib inline    # Graphiques dans notebook
In [225]: %matplotlib notebook  # Graphiques interactifs
In [226]: %matplotlib widget    # Graphiques interactifs (JupyterLab)
In [227]: %matplotlib qt        # Fenêtre Qt
In [228]: %matplotlib tk        # Fenêtre Tk
In [229]: %matplotlib osx       # macOS natif
In [230]: %matplotlib            # Affiche backend actuel

# %pylab : Import numpy + matplotlib (déprécié)
In [231]: %pylab                # Import * de numpy et pyplot
# Mieux vaut faire imports explicites


# === NOTEBOOK / JUPYTER ===

# %notebook : Exporter en notebook
In [232]: %notebook output.ipynb  # Exporte session actuelle
In [233]: %notebook -e output.ipynb 1-50  # Commandes 1-50

# %qtconsole : Lancer Qt console
In [234]: %qtconsole            # Ouvre nouvelle console Qt

# %connect_info : Infos connexion kernel
In [235]: %connect_info
{
  "shell_port": 12345,
  "iopub_port": 12346,
  ...
}

# %gui : Changer event loop GUI
In [236]: %gui qt               # Qt event loop
In [237]: %gui wx               # wxPython
In [238]: %gui tk               # Tkinter
In [239]: %gui gtk              # GTK
In [240]: %gui osx              # macOS
In [241]: %gui                  # Affiche GUI actuel


# === AUTORELOAD (Extension) ===

In [242]: %load_ext autoreload

# %autoreload : Mode de rechargement
In [243]: %autoreload 0         # Désactivé
In [244]: %autoreload 1         # Recharge modules importés avec %aimport
In [245]: %autoreload 2         # Recharge tous les modules
In [246]: %autoreload 3         # Recharge + exécute fonctions décorées

# %aimport : Spécifier modules à recharger (mode 1)
In [247]: %aimport my_module
In [248]: %aimport -my_module   # Exclure module (mode 2)


# === LINE_PROFILER (Extension) ===

# Installer: pip install line_profiler
In [249]: %load_ext line_profiler

# %lprun : Profiler ligne par ligne
In [250]: %lprun -f function_name function_name(args)
In [251]: %lprun -f func1 -f func2 main_function()  # Plusieurs fonctions

# Exemple complet:
def slow_function(n):
    total = 0
    for i in range(n):
        total += i ** 2
    return total

In [252]: %lprun -f slow_function slow_function(10000)
Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     1                                           def slow_function(n):
     2         1          2.0      2.0      0.0      total = 0
     3     10001      15234.0      1.5     45.2      for i in range(n):
     4     10000      18456.0      1.8     54.8          total += i ** 2
     5         1          1.0      1.0      0.0      return total


# === MEMORY_PROFILER (Extension) ===

# Installer: pip install memory_profiler
In [253]: %load_ext memory_profiler

# %memit : Mesurer mémoire d'une ligne
In [254]: %memit sum(range(1000000))
peak memory: 52.34 MiB, increment: 0.08 MiB

In [255]: %memit -r 5 sum(range(1000000))  # 5 répétitions

# %mprun : Profiler mémoire ligne par ligne
# Fonction doit être dans fichier séparé
# my_module.py:
# def memory_hungry():
#     x = [i**2 for i in range(100000)]
#     return sum(x)

In [256]: from my_module import memory_hungry
In [257]: %mprun -f memory_hungry memory_hungry()

# %%memit : Mesurer mémoire cellule
In [258]: %%memit
     ...: x = [i**2 for i in range(100000)]
     ...: sum(x)


# === SQL (Extension) ===

# Installer: pip install ipython-sql
In [259]: %load_ext sql

# %sql : Requête SQL simple
In [260]: %sql sqlite:///database.db
In [261]: %sql SELECT * FROM users LIMIT 5

# %%sql : Requête SQL multi-lignes
In [262]: %%sql
     ...: SELECT name, age
     ...: FROM users
     ...: WHERE age > 25
     ...: ORDER BY age DESC

# Connexion à différentes bases
In [263]: %sql postgresql://user:pass@localhost/dbname
In [264]: %sql mysql://user:pass@localhost/dbname
In [265]: %sql sqlite:///mydb.db

# Stocker résultat dans variable
In [266]: result = %sql SELECT * FROM users
In [267]: df = result.DataFrame()  # Convertir en pandas DataFrame

# %sql_config : Configuration SQL
In [268]: %config SqlMagic.autopandas = True  # Auto-conversion DataFrame


# === CYTHON (Extension) ===

# Installer: pip install cython
In [269]: %load_ext cython

# %%cython : Compiler code Cython
In [270]: %%cython
     ...: def fast_sum(int n):
     ...:     cdef int i, total = 0
     ...:     for i in range(n):
     ...:         total += i
     ...:     return total

In [271]: fast_sum(1000000)     # Fonction compilée disponible

# Avec annotations
In [272]: %%cython -a
     ...: def annotated_function(int x):
     ...:     return x ** 2
# -a : Affiche annotation HTML (highlighting code Python)

# Compiler avec flags
In [273]: %%cython --compile-args=-O3
     ...: # Code optimisé


# === RMAGIC (Extension R) ===

# Installer: pip install rpy2
In [274]: %load_ext rpy2.ipython

# %R : Exécuter commande R simple
In [275]: %R x <- c(1, 2, 3, 4, 5); mean(x)

# %%R : Code R multi-lignes
In [276]: %%R
     ...: data <- data.frame(
     ...:     x = 1:10,
     ...:     y = rnorm(10)
     ...: )
     ...: plot(data$x, data$y)

# Transfert Python <-> R
In [277]: import numpy as np
In [278]: py_data = np.array([1, 2, 3, 4, 5])
In [279]: %R -i py_data        # Import Python -> R
In [280]: %R mean(py_data)

In [281]: %R -o result result <- mean(py_data)  # Export R -> Python
In [282]: print(result)         # Variable Python


# === SCRIPT (Extension) ===

# %%script : Exécuter avec interpréteur personnalisé
In [283]: %%script python
     ...: print("Hello from Python")

In [284]: %%script ruby
     ...: puts "Hello from Ruby"

In [285]: %%script perl
     ...: print "Hello from Perl\n";

In [286]: %%script bash
     ...: echo "Hello from Bash"
     ...: ls -la

In [287]: %%script node
     ...: console.log("Hello from Node.js");


# === CELL MAGICS (Cellule complète) ===

# %%writefile : Écrire cellule dans fichier
In [288]: %%writefile script.py
     ...: def hello():
     ...:     print("Hello, World!")
     ...:
     ...: if __name__ == "__main__":
     ...:     hello()

In [289]: %%writefile -a script.py  # Append
     ...: # Plus de code

# %%file : Alias de %%writefile
In [290]: %%file output.txt
     ...: Contenu du fichier
     ...: Sur plusieurs lignes

# %%bash : Exécuter Bash
In [291]: %%bash
     ...: echo "Script Bash"
     ...: for i in {1..5}; do
     ...:     echo "Ligne $i"
     ...: done

# %%sh : Alias pour bash
In [292]: %%sh
     ...: pwd
     ...: ls

# %%python : Exécuter Python explicitement
In [293]: %%python
     ...: print("Python explicite")

# %%python2 : Exécuter avec Python 2
In [294]: %%python2
     ...: print "Python 2 syntax"

# %%python3 : Exécuter avec Python 3
In [295]: %%python3
     ...: print("Python 3 syntax")

# %%ruby : Exécuter Ruby
In [296]: %%ruby
     ...: puts "Hello from Ruby"
     ...: [1, 2, 3].each { |n| puts n * 2 }

# %%perl : Exécuter Perl
In [297]: %%perl
     ...: print "Hello from Perl\n";
     ...: my @array = (1, 2, 3, 4, 5);
     ...: print "@array\n";

# %%javascript / %%js : JavaScript (Jupyter)
In [298]: %%javascript
     ...: console.log("Hello from JavaScript");
     ...: element.text("Texte modifié");

# %%html : Afficher HTML
In [299]: %%html
     ...: <h1>Titre HTML</h1>
     ...: <p>Paragraphe avec <strong>gras</strong></p>
     ...: <ul>
     ...:     <li>Item 1</li>
     ...:     <li>Item 2</li>
     ...: </ul>

# %%latex : Afficher LaTeX
In [300]: %%latex
     ...: \begin{equation}
     ...: E = mc^2
     ...: \end{equation}
     ...:
     ...: \begin{align}
     ...: f(x) &= x^2 + 2x + 1 \\
     ...: &= (x + 1)^2
     ...: \end{align}

# %%markdown : Afficher Markdown
In [301]: %%markdown
     ...: # Titre Principal
     ...:
     ...: ## Sous-titre
     ...:
     ...: **Gras** et *italique*
     ...:
     ...: - Liste
     ...: - D'items
     ...:
     ...: ```python
     ...: print("Code")
     ...: ```

# %%svg : Afficher SVG
In [302]: %%svg
     ...: <svg width="100" height="100">
     ...:     <circle cx="50" cy="50" r="40" fill="blue" />
     ...: </svg>

# %%capture : Capturer sortie
In [303]: %%capture output
     ...: print("Ceci est capturé")
     ...: print("Pas affiché directement")
     ...: x = 42

In [304]: print(output.stdout)   # Afficher sortie capturée
In [305]: print(output.stderr)   # Erreurs capturées
In [306]: output.show()          # Afficher tout

# Capturer sans stocker
In [307]: %%capture
     ...: print("Supprimé")

# %%debug : Déboguer cellule
In [308]: %%debug
     ...: x = 1
     ...: y = 0
     ...: z = x / y               # Erreur -> lance pdb


# === COMMANDES AVANCÉES ===

# %killbgscripts : Tuer scripts background
In [309]: %killbgscripts

# %gui : Event loop GUI (déjà vu)

# %pylab : Import numpy + matplotlib (déprécié)
In [310]: %pylab inline
# Importe: numpy as np, matplotlib.pyplot as plt
# Mieux vaut: import numpy as np; import matplotlib.pyplot as plt

# %doctest_mode : Mode doctest
In [311]: %doctest_mode
# Active >>> prompt et supprime Out[]
>>> x = 5
>>> x + 2
7

# %install_ext : Installer extension depuis URL (déprécié)
# Remplacé par pip install

# %install_profiles : Installer profils (déprécié)

# %load_ext : Charger extension (déjà vu détaillé)

# %unload_ext : Décharger extension

# %reload_ext : Recharger extension


# === COMMANDES SPÉCIALES VARIABLES ===

# Variables automatiques IPython:

# _ : Dernière sortie
In [312]: 2 + 2
Out[312]: 4

In [313]: _
Out[313]: 4

# __ : Avant-dernière sortie
In [314]: __
Out[314]: 4

# ___ : Avant-avant-dernière sortie
In [315]: ___
Out[315]: 4

# _N : Sortie numéro N
In [316]: _312
Out[316]: 4

# _iN : Entrée numéro N
In [317]: _i312
Out[317]: '2 + 2'

# _ih : Liste de toutes les entrées
In [318]: _ih[312]
Out[318]: '2 + 2'

# _oh : Dictionnaire de toutes les sorties
In [319]: _oh[312]
Out[319]: 4

# _dh : Historique des dossiers
In [320]: _dh
Out[320]: ['/home/user/project', '/home/user/data']

# _exit_code : Code sortie dernière commande shell
In [321]: !ls non_existent_file
In [322]: _exit_code
Out[322]: 2


[OK] PERSONNALISATION AVANCÉE


# === Créer ses propres magic commands ===

from IPython.core.magic import register_line_magic, register_cell_magic

# Line magic personnalisée
@register_line_magic
def hello(line):
    """Dit bonjour"""
    return f"Bonjour {line}!"

In [323]: %hello Alice
Out[323]: 'Bonjour Alice!'

# Cell magic personnalisée
@register_cell_magic
def reverse(line, cell):
    """Inverse le texte de la cellule"""
    return cell[::-1]

In [324]: %%reverse
     ...: Hello World
Out[324]: 'dlroW olleH'

# Magic hybride (line et cell)
from IPython.core.magic import register_line_cell_magic

@register_line_cell_magic
def my_magic(line, cell=None):
    if cell is None:
        # Appelé comme line magic
        return f"Line: {line}"
    else:
        # Appelé comme cell magic
        return f"Cell: {cell}"

In [325]: %my_magic test
Out[325]: 'Line: test'

In [326]: %%my_magic
     ...: contenu
Out[326]: 'Cell: contenu'

# Supprimer magic personnalisée
del hello
del reverse


# === Hooks IPython ===

# Pre-execute hook (avant chaque commande)
def pre_run_hook():
    print("Avant exécution")

ip = get_ipython()
ip.events.register('pre_execute', pre_run_hook)

# Post-execute hook (après chaque commande)
def post_run_hook():
    print("Après exécution")

ip.events.register('post_execute', post_run_hook)

# Hook sur erreur
def error_hook():
    print("Une erreur s'est produite!")

ip.events.register('post_execute', error_hook)

# Désinscrire hook
ip.events.unregister('pre_execute', pre_run_hook)


[OK] IPYTHON POUR DATA SCIENCE


# === Workflow Data Science typique ===

# 1. Imports standards
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

%matplotlib inline
%load_ext autoreload
%autoreload 2

# 2. Configuration affichage
%precision 2
pd.set_option('display.max_rows', 100)
pd.set_option('display.max_columns', 50)

# 3. Charger données
df = pd.read_csv('data.csv')

# 4. Explorer rapidement
%whos                           # Variables
df.head()                       # Premières lignes
df.info()                       # Infos
df.describe()                   # Statistiques

# 5. Profiler code lent
%%time
result = df.groupby('category').mean()

%%timeit
df['new_col'] = df['col1'] * df['col2']

# 6. Déboguer erreur
%debug                          # Si erreur

# 7. Sauvegarder travail important
%store df
%save analysis.py 1-50


# === Astuces Data Science ===

# Afficher toutes les colonnes DataFrame
pd.set_option('display.max_columns', None)

# Afficher plus de lignes
pd.set_option('display.max_rows', 200)

# Format flottants
pd.options.display.float_format = '{:.2f}'.format

# Recharger module modifié
%load_ext autoreload
%autoreload 2

# Timer requête lente
%%time
result = df.query('age > 30 and salary > 50000')

# Profiler fonction
%prun df.groupby('category').agg({'value': ['mean', 'sum', 'count']})

# Mémoire DataFrame
df.memory_usage(deep=True).sum() / 1024**2  # En MB

# Avec magic:
%memit df = pd.read_csv('large_file.csv')


[OK] COMPARAISON SHELL PYTHON VS IPYTHON


# === Python Standard ===
python                          # Shell basique
>>> 2 + 2
4
>>> # Pas d'auto-complétion avancée
>>> # Pas de magic commands
>>> # Pas de couleurs
>>> quit()

# === IPython ===
ipython                         # Shell enrichi
In [1]: 2 + 2                  # Numérotation
Out[1]: 4                      # Sortie numérotée

In [2]: import pandas<TAB>     # Auto-complétion
In [3]: pandas?                # Aide rapide
In [4]: %timeit sum(range(1000))  # Magic commands
In [5]: !ls                    # Commandes shell
In [6]: _ + 10                 # Référence sortie précédente
Out[6]: 14


[OK] ERREURS COURANTES ET SOLUTIONS


# === PROBLÈME: Magic command not found ===
# Erreur: UsageError: Line magic function `%command` not found

# Solution 1: Vérifier spelling
In [1]: %lsmagic               # Lister commandes disponibles

# Solution 2: Charger extension
In [2]: %load_ext extension_name

# Solution 3: Automagic désactivé
In [3]: %automagic on


# === PROBLÈME: Extension introuvable ===
# Erreur: ModuleNotFoundError: No module named 'extension'

# Solution: Installer extension
!pip install ipython-sql        # Pour SQL
!pip install line_profiler      # Pour lprun
!pip install memory_profiler    # Pour memit/mprun
!pip install cython             # Pour cython
!pip install rpy2               # Pour R


# === PROBLÈME: Variable écrasée ===
# Utiliser namespace séparé pour %run

In [4]: x = 42
In [5]: %run script.py          # script.py définit x = 100
In [6]: x                       # x = 100 (écrasé!)

# Solution: %run sans -i (namespace séparé)
In [7]: x = 42
In [8]: %run script.py          # script.py ne voit pas x
In [9]: x                       # x = 42 (préservé)


# === PROBLÈME: Historique perdu ===
# L'historique est stocké dans SQLite

# Localisation:
# Linux/Mac: ~/.ipython/profile_default/history.sqlite
# Windows: %USERPROFILE%\.ipython\profile_default\history.sqlite

# Solution: Backup régulier
!cp ~/.ipython/profile_default/history.sqlite ~/backup/


# === PROBLÈME: IPython lent ===

# Solution 1: Désactiver features non utilisées
c.TerminalInteractiveShell.automagic = False
c.IPCompleter.use_jedi = False

# Solution 2: Nettoyer historique
%reset -f
%reset -s                       # Reset + historique

# Solution 3: Historique en mémoire
c.HistoryManager.hist_file = ':memory:'


# === PROBLÈME: Matplotlib ne s'affiche pas ===

# Solution:
%matplotlib inline              # Jupyter
%matplotlib qt                  # Fenêtre séparée
%matplotlib notebook            # Interactif (notebook)


[OK] BONNES PRATIQUES IPYTHON


# === 1. Organisation du code ===

# [OK] BON: Utiliser %autoreload pour développement
%load_ext autoreload
%autoreload 2
from mymodule import myfunction  # Se recharge automatiquement

# [X] MAUVAIS: Tout coder dans notebook
# Mettre logique dans fichiers .py réutilisables

# === 2. Performance ===

# [OK] BON: Utiliser %timeit pour optimiser
%timeit [x**2 for x in range(1000)]
%timeit list(map(lambda x: x**2, range(1000)))

# [X] MAUVAIS: Optimiser sans mesurer

# === 3. Debugging ===

# [OK] BON: Activer %pdb pendant développement
%pdb on

# [OK] BON: Utiliser %debug après erreur
try:
    buggy_function()
except:
    %debug

# [X] MAUVAIS: print() debugging partout

# === 4. Documentation ===

# [OK] BON: Utiliser ? et ?? souvent
pandas.DataFrame?               # Documentation rapide
pandas.DataFrame??              # Avec code source

# [OK] BON: %psearch pour découvrir
%psearch os.*dir*               # Trouver fonctions

# === 5. Historique ===

# [OK] BON: Sauvegarder code important
%save analysis.py 1-50          # Sauvegarder commandes

# [OK] BON: Utiliser %macro pour répéter
%macro data_cleaning 10-20      # Macro de nettoyage

# [X] MAUVAIS: Tout refaire manuellement

# === 6. Variables ===

# [OK] BON: Nettoyer namespace régulièrement
%reset -f
%whos                           # Vérifier ce qui reste

# [X] MAUVAIS: Accumuler variables inutiles

# === 7. Magic commands ===

# [OK] BON: Utiliser magic appropriées
%run script.py                  # Pour scripts
%%timeit                        # Pour benchmarks
%debug                          # Pour debugging

# [X] MAUVAIS: Tout faire manuellement

# === 8. Extensions ===

# [OK] BON: Charger au besoin
%load_ext autoreload            # Développement
%load_ext line_profiler         # Profiling

# [X] MAUVAIS: Charger toutes les extensions
# (Ralentit démarrage)

# === 9. Configuration ===

# [OK] BON: Personnaliser ipython_config.py
# Charger modules courants
# Définir raccourcis
# Configurer affichage

# [X] MAUVAIS: Retaper configs à chaque fois

# === 10. Notebook vs Script ===

# [OK] BON: Notebook pour exploration
# [OK] BON: Script .py pour code production
# [OK] BON: Tester dans notebook, refactorer en script

# [X] MAUVAIS: Code production dans notebook


[OK] ASTUCES PRODUCTIVITÉ


# === Raccourcis personnalisés ===

# Dans ipython_config.py:
c.TerminalInteractiveShell.shortcuts = [
    ('c-k', 'kill-line'),           # Ctrl+K: couper fin ligne
    ('c-u', 'unix-line-discard'),   # Ctrl+U: couper début ligne
]

# === Aliases shell utiles ===
%alias ll ls -lah
%alias g git
%alias p python
%alias v vim

# === Fonctions de démarrage ===

# Dans ~/.ipython/profile_default/startup/00-imports.py:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pprint import pprint

print("[OK] Modules chargés: numpy, pandas, matplotlib")

# === Macro utiles ===

# Macro nettoyage données
%macro clean_data 10-15

# Macro visualisation
%macro viz 20-25

# === Format d'affichage ===

# Dates lisibles
pd.set_option('display.date_format', '%Y-%m-%d')

# Nombres avec séparateurs
pd.options.display.float_format = '{:,.2f}'.format

# === Gestion mémoire ===

# Supprimer grandes variables
%xdel large_dataframe

# Vérifier mémoire
%whos                           # Voir tailles

# === Templating ===

# Créer template notebook
%%writefile template.ipynb
{
 "cells": [
  {
   "cell_type": "code",
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "%load_ext autoreload\n",
    "%autoreload 2"
   ]
  }
 ]
}


[OK] INTÉGRATION AVEC OUTILS


# === Git ===
%cd ~/projects/myproject
!git status
!git add .
!git commit -m "Update analysis"
!git push

# === Virtual Environments ===
!source venv/bin/activate       # Bash
%pip install package            # Installe dans venv actif

# === Docker ===
!docker ps
!docker exec -it container bash

# === Jupyter ===
jupyter notebook                # Lancer notebook
%notebook output.ipynb          # Exporter session

# === VSCode ===
# IPython fonctionne dans VSCode interactive window
# Utiliser #%% pour définir cellules

# === PyCharm ===
# IPython console disponible
# Outils -> Python Console -> Use IPython


[OK] RESSOURCES ET AIDE


# === Documentation ===
%quickref                       # Référence rapide
%magic                          # Documentation magic commands
?                               # Introduction IPython

# === Aide sur objet ===
object?                         # Aide rapide
object??                        # Code source
%pinfo object                   # Alias de ?
%pdoc object                    # Docstring seule
%psource object                 # Code source seul

# === Sites officiels ===
# IPython: https://ipython.org/
# Documentation: https://ipython.readthedocs.io/
# Jupyter: https://jupyter.org/

# === Commandes utiles aide ===
%lsmagic                        # Toutes les magic commands
dir(object)                     # Attributs et méthodes
help(object)                    # Aide Python standard
type(object)                    # Type de l'objet
vars()                          # Variables dans namespace


[OK] EXEMPLES PRATIQUES COMPLETS


# === Exemple 1: Analyse de données ===

# Setup
import pandas as pd
import numpy as np
%matplotlib inline
%load_ext autoreload
%autoreload 2

# Charger données
%time df = pd.read_csv('sales_data.csv')

# Explorer
%whos
df.head()
df.info()

# Analyser performance
%%timeit
monthly_sales = df.groupby('month')['sales'].sum()

# Profiler code lent
%prun df.groupby(['region', 'product']).agg({'sales': 'sum', 'quantity': 'mean'})

# Sauvegarder travail
%save data_analysis.py 1-20


# === Exemple 2: Développement module ===

# my_module.py
def process_data(data):
    return [x * 2 for x in data]

# IPython
%load_ext autoreload
%autoreload 2

from my_module import process_data

# Modifier my_module.py -> changements automatiques
result = process_data([1, 2, 3])  # Utilise version à jour

# Tester performance
%timeit process_data(range(10000))

# Profiler
%lprun -f process_data process_data(range(10000))


# === Exemple 3: Machine Learning ===

import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
%load_ext autoreload

# Charger données
%time X, y = load_data()

# Split
X_train, X_test, y_train, y_test = train_test_split(X, y)

# Entraîner avec timing
%%time
model = RandomForestClassifier(n_estimators=100)
model.fit(X_train, y_train)

# Évaluer
score = model.score(X_test, y_test)
print(f"Accuracy: {score:.2%}")

# Profiler prédiction
%prun predictions = model.predict(X_test)

# Sauvegarder modèle et variables importantes
%store model
%store X_test
%store y_test


# === Exemple 4: Web Scraping et Debug ===

import requests
from bs4 import BeautifulSoup

%pdb on  # Debug automatique

def scrape_page(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.content, 'html.parser')
    return soup.find_all('a')

# Si erreur dans scrape_page, pdb démarre automatiquement
links = scrape_page('https://example.com')

# Mesurer temps requête
%timeit requests.get('https://example.com')

# Voir variables définies
%whos


# === Exemple 5: Visualisation interactive ===

import matplotlib.pyplot as plt
import numpy as np
%matplotlib notebook  # Interactif

# Générer données
x = np.linspace(0, 10, 100)
y = np.sin(x)

# Plot avec timing
%%time
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(x, y)
ax.set_title('Sine Wave')
plt.show()

# Sauvegarder figure
!mkdir -p figures
%save figures/plot_code.py 1-10


[OK] CHEATSHEET RAPIDE


# Commandes essentielles:
?                   # Aide
%lsmagic            # Lister magic commands
%quickref           # Référence rapide
object?             # Aide sur objet
object??            # Code source

# Exécution:
%run script.py      # Exécuter script
%timeit code        # Benchmark
%time code          # Timer
%prun code          # Profiler

# Variables:
%who                # Lister variables
%whos               # Détails variables
%reset              # Supprimer variables
%store var          # Sauvegarder variable

# Historique:
%history            # Voir historique
%recall 5           # Rappeler commande 5
%save file.py 1-10  # Sauvegarder commandes
%macro name 1-5     # Créer macro

# Debugging:
%debug              # Déboguer erreur
%pdb on             # Auto-debug

# Système:
!command            # Commande shell
%cd /path           # Changer dossier
%pwd                # Dossier actuel
%ls                 # Lister fichiers

# Extensions:
%load_ext name      # Charger extension
%autoreload 2       # Recharger modules

# Jupyter:
%matplotlib inline  # Graphiques inline
%%html              # Cellule HTML
%%time              # Timer cellule


[OK] DIFFÉRENCES IPYTHON VS JUPYTER


# IPython = Shell interactif Python amélioré
# Jupyter = Interface notebook (utilise IPython comme kernel)

# IPython (terminal):
ipython
In [1]: print("Hello")
Hello

# Jupyter (navigateur):
jupyter notebook
# Cellules avec rendu riche (HTML, images, LaTeX)

# Commun:
# - Toutes les magic commands
# - Auto-complétion
# - Aide avec ?
# - Historique

# Spécifique Jupyter:
# - %%html, %%markdown, %%latex
# - Affichage images/graphiques enrichi
# - Export en différents formats
# - Partage facile

# Spécifique IPython terminal:
# - Plus rapide
# - Moins de ressources
# - Intégration shell meilleure


[OK] CONCLUSION


# IPython est essentiel pour:
# [OK] Développement interactif Python
# [OK] Exploration de données
# [OK] Prototypage rapide
# [OK] Debugging efficace
# [OK] Analyse de performance
# [OK] Apprentissage Python

# Commencer avec:
ipython
%quickref               # Lire la référence rapide
%lsmagic                # Explorer les commandes
object?                 # Utiliser l'aide
%timeit code            # Mesurer performance
%debug                  # Déboguer

# Progresser avec:
%load_ext autoreload    # Développement
%lprun                  # Profiling avancé
%macro                  # Automatisation
Configuration avancée   # Personnalisation

# Maîtriser:
# - Extensions (SQL, Cython, R)
# - Magic commands personnalisées
# - Integration complète workflow
# - Jupyter notebooks avancés


# Pour aller plus loin:
# https://ipython.readthedocs.io/
# https://ipython.org/documentation.html
# https://jakevdp.github.io/PythonDataScienceHandbook/