Skip to content

Instantly share code, notes, and snippets.

@dzogrim
Created January 31, 2025 08:38
Show Gist options
  • Save dzogrim/1ef4c61637fd6ad0f4182ea8e3180b28 to your computer and use it in GitHub Desktop.
Save dzogrim/1ef4c61637fd6ad0f4182ea8e3180b28 to your computer and use it in GitHub Desktop.
Script Python pour détecter le type MIME et le type détaillé d'un fichier en utilisant libmagic
#!/usr/bin/env python3.9
"""
Script pour détecter le type MIME et le type détaillé d'un fichier en utilisant libmagic.
Installation nécessaire au préalable de la dépendance :
pip3 install python-magic
Usage :
python file_magic.py <chemin_du_fichier>
"""
import sys
import os
import logging
import magic
from typing import Tuple
# Configuration du logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
def detect_file_type(file_path: str) -> Tuple[str, str]:
"""
Détecte le type MIME et le type détaillé d'un fichier.
Args:
file_path (str): Chemin du fichier à analyser.
Returns:
Tuple[str, str]: Type MIME et type détaillé du fichier.
Raises:
FileNotFoundError: Si le fichier n'existe pas.
Exception: Si la détection échoue pour une raison quelconque.
"""
if not os.path.isfile(file_path):
raise FileNotFoundError(f"Le fichier '{file_path}' n'existe pas.")
try:
mime_detector = magic.Magic(mime=True)
detailed_detector = magic.Magic()
type_mime = mime_detector.from_file(file_path)
type_detaille = detailed_detector.from_file(file_path)
return type_mime, type_detaille
except Exception as e:
raise RuntimeError(f"Erreur lors de la détection du type de fichier : {e}")
def main():
"""
Fonction principale : Vérifie les arguments et affiche le type du fichier.
"""
if len(sys.argv) != 2:
logging.error("Usage : python file_magic.py <chemin_du_fichier>")
sys.exit(1)
file_path = sys.argv[1]
try:
type_mime, type_detaille = detect_file_type(file_path)
logging.info(f"Type MIME : {type_mime}")
logging.info(f"Type détaillé : {type_detaille}")
except FileNotFoundError as fnf_error:
logging.error(fnf_error)
sys.exit(1)
except Exception as e:
logging.error(e)
sys.exit(1)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment