IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Python Discussion :

Obtenir Executable à partir d'une extension de fichier


Sujet :

Python

  1. #1
    Membre confirmé
    Homme Profil pro
    Apprenti dev Python
    Inscrit en
    Août 2021
    Messages
    69
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Apprenti dev Python

    Informations forums :
    Inscription : Août 2021
    Messages : 69
    Par défaut Obtenir Executable à partir d'une extension de fichier
    Bonjour,
    Je cherche à obtenir le chemin d'accès de l'exécutable qui ouvre un fichier en se basant sur l'extension (Je suis sous Windows). Par exemple:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    app_path = get_app_path('.txt')
    >>> r'chemin\vers\notepad.exe'
    J'ai actuellement un code (un peu indigeste je reconnais ) qui fonctionne mais pas parfaitement, certaines application ne fonctionnent pas
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    import os
    import shlex
    import winreg
    import logging
     
    # Configure logging
    logging.basicConfig(level=logging.DEBUG, format='%(levelname)s: %(message)s')
     
    def get_app_path(ext):
        # Attempt to retrieve from UserChoice
        try:
            with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{}\UserChoice'.format(ext)) as key:
                progid = winreg.QueryValueEx(key, 'ProgId')[0]
            with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'SOFTWARE\Classes\{}\shell\open\command'.format(progid)) as key:
                path = winreg.QueryValueEx(key, '')[0]
                return clean_path(path)
        except FileNotFoundError as e:
            logging.debug(f"UserChoice lookup failed for {ext}: {e}")
     
        # Try HKEY_CLASSES_ROOT
        try:
            class_root = winreg.QueryValue(winreg.HKEY_CLASSES_ROOT, ext)
            if class_root:
                with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r'{}\shell\open\command'.format(class_root)) as key:
                    path = winreg.QueryValueEx(key, '')[0]
                    return clean_path(path)
        except FileNotFoundError as e:
            logging.debug(f"HKEY_CLASSES_ROOT lookup failed for {ext}: {e}")
     
        # Try HKEY_LOCAL_MACHINE
        try:
            with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Classes\{}\shell\open\command'.format(ext)) as key:
                path = winreg.QueryValueEx(key, '')[0]
                return clean_path(path)
        except FileNotFoundError as e:
            logging.debug(f"HKEY_LOCAL_MACHINE lookup failed for {ext}: {e}")
     
        # Try OpenWithProgids
        try:
            with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r'{}\OpenWithProgids'.format(ext)) as key:
                progid = winreg.EnumValue(key, 0)[0]
            with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r'{}\shell\open\command'.format(progid)) as key:
                path = winreg.QueryValueEx(key, '')[0]
                return clean_path(path)
        except FileNotFoundError as e:
            logging.debug(f"OpenWithProgids lookup failed for {ext}: {e}")
     
        # Try OpenWithList
        try:
            with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{}\OpenWithList'.format(ext)) as key:
                progid = winreg.EnumValue(key, 0)[0]
            with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r'{}\shell\open\command'.format(progid)) as key:
                path = winreg.QueryValueEx(key, '')[0]
                return clean_path(path)
        except FileNotFoundError as e:
            logging.debug(f"OpenWithList lookup failed for {ext}: {e}")
     
        # If no path is found, return None
        return None
     
    def clean_path(path):
        path = os.path.expandvars(path)
        path = shlex.split(path, posix=False)[0]
        return path.strip('"')
     
    # Extensions to check (examples)
    extensions = ['.txt', '.pdf', '.jpg', '.png', '.pptx', '.py', '.svg', '.php']
     
    # Print the associated program for each extension
    for extension in extensions:
        app_path = get_app_path(extension)
        print(f'Extension: {extension}, Program: {app_path}')
    RESULAT:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    Extension: .txt, Program: C:\Program Files\WindowsApps\Microsoft.WindowsNotepad_11.2501.31.0_x64__8wekyb3d8bbwe\Notepad\Notepad.exe
    Extension: .pdf, Program: C:\Users\...\AppData\Local\Programs\Opera\opera.exe
    Extension: .jpg, Program: None
    Extension: .png, Program: None
    Extension: .pptx, Program: C:\Program Files\Microsoft Office\Root\Office16\POWERPNT.EXE
    Extension: .py, Program: C:\Users\...\AppData\Local\Programs\Python\Launcher\py.exe
    Extension: .svg, Program: C:\Program Files\Inkscape\bin\inkscape.exe
    Extension: .php, Program: C:\Users\...\AppData\Local\Programs\Microsoft VS Code\Code.exe
    RESULTAT (logs):
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    DEBUG: UserChoice lookup failed for .jpg: [WinError 2] Le fichier spécifié est introuvable
    DEBUG: HKEY_CLASSES_ROOT lookup failed for .jpg: [WinError 2] Le fichier spécifié est introuvable
    DEBUG: HKEY_LOCAL_MACHINE lookup failed for .jpg: [WinError 2] Le fichier spécifié est introuvable
    DEBUG: OpenWithProgids lookup failed for .jpg: [WinError 2] Le fichier spécifié est introuvable
    DEBUG: OpenWithList lookup failed for .jpg: [WinError 2] Le fichier spécifié est introuvable
    DEBUG: UserChoice lookup failed for .png: [WinError 2] Le fichier spécifié est introuvable
    DEBUG: HKEY_CLASSES_ROOT lookup failed for .png: [WinError 2] Le fichier spécifié est introuvable
    DEBUG: HKEY_LOCAL_MACHINE lookup failed for .png: [WinError 2] Le fichier spécifié est introuvable
    DEBUG: OpenWithProgids lookup failed for .png: [WinError 2] Le fichier spécifié est introuvable
    DEBUG: OpenWithList lookup failed for .png: [WinError 2] Le fichier spécifié est introuvable
    DEBUG: UserChoice lookup failed for .pptx: [WinError 2] Le fichier spécifié est introuvable
    DEBUG: UserChoice lookup failed for .py: [WinError 2] Le fichier spécifié est introuvable
    DEBUG: UserChoice lookup failed for .php: [WinError 2] Le fichier spécifié est introuvable
    DEBUG: HKEY_LOCAL_MACHINE lookup failed for .php: [WinError 2] Le fichier spécifié est introuvable
    IMPORTANT:
    Le code ci-dessus provient de diverses sources (autres forums, IA génératives, etc...), elles ont été bien pratiques mais malheureusement insuffisantes, d'où ce post.

    Merci par avance de vos réponses

    Dymon

  2. #2
    Expert éminent
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 715
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 715
    Par défaut
    Salut,

    Si vous obtenez la même chose que les commandes windows assoc et ftype, difficile de faire mieux(*). Personnellement, je ne vois pas trop l'intérêt de re-écrire de telles commandes: on peut tout de même les utiliser depuis un programme python via subprocess.
    (*) s'il n'y a pas de programme associé une extension (comme .jpg), pourquoi ça devrait en trouver une?

    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

  3. #3
    Membre Expert
    Profil pro
    Inscrit en
    Septembre 2010
    Messages
    1 530
    Détails du profil
    Informations personnelles :
    Âge : 46
    Localisation : France

    Informations forums :
    Inscription : Septembre 2010
    Messages : 1 530
    Par défaut
    ceux qui a priori ne fonctionnent pas semblent être pour les applications type Store (application Photos pour les jpg et png) et leur association est différente il me semble (vu que ce ne sont pas vraiment des .exe), et qu'ils sont (de mémoire) dans un dossier masqué (voir système)

  4. #4
    Membre confirmé
    Homme Profil pro
    Apprenti dev Python
    Inscrit en
    Août 2021
    Messages
    69
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Apprenti dev Python

    Informations forums :
    Inscription : Août 2021
    Messages : 69
    Par défaut
    Citation Envoyé par umfred Voir le message
    ceux qui a priori ne fonctionnent pas semblent être pour les applications type Store (application Photos pour les jpg et png) et leur association est différente il me semble (vu que ce ne sont pas vraiment des .exe), et qu'ils sont (de mémoire) dans un dossier masqué (voir système)
    Effectivement, le dossier des applications Windows (type Store) sont dans le dossier caché et interdit en lecture: C:\Program Files\WindowsApps

  5. #5
    Membre confirmé
    Homme Profil pro
    Apprenti dev Python
    Inscrit en
    Août 2021
    Messages
    69
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Apprenti dev Python

    Informations forums :
    Inscription : Août 2021
    Messages : 69
    Par défaut
    Après de nombreuses recherches au travers des fabuleux registres Windows voici un code qui fonctionne...
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    import os
    import shlex
    import winreg
     
     
    def query_registry_value(root_key, key_path, value_name):
        """
        Helper function to query a registry value.
        :param root_key: root key of the registry, like winreg.HKEY_...
        :param key_path: path of the desired path
        :param value_name: value of the previous path
        """
        try:
            with winreg.OpenKey(root_key, key_path) as key:
                return winreg.QueryValueEx(key, value_name)[0]
     
        except FileNotFoundError as e:
            return None
     
    def enum_registry_value(root_key, key_path, index):
        """
        Helper function to enumerate registry value.
        :param root_key: root key of the registry, like winreg.HKEY_...
        :param key_path: path of the desired path
        :param index: index to get
        """
        try:
            with winreg.OpenKey(root_key, key_path) as key:
                return winreg.EnumValue(key, index)[0]
     
        except (FileNotFoundError, OSError )as e:
            return None
     
     
    def clean_path(path):
        path = os.path.expandvars(path)
        path = shlex.split(path, posix=False)[0]
        path = path.strip('"')
        return path
     
     
    def get_app_path(ext):
        """Function to get the application path associated with a file extension."""
        # Try to get ProgID from UserChoice in HKEY_CURRENT_USER
        prog_id = query_registry_value(winreg.HKEY_CURRENT_USER, fr'Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{ext}\UserChoice', 'ProgId')
        if prog_id:
            path = query_registry_value(winreg.HKEY_CURRENT_USER, fr'Software\Classes\{prog_id}\shell\open\command', '')
            if path:
                return clean_path(path)
     
            # Try to get path from HKEY_CLASSES_ROOT using ProgID for Microsoft Apps
            package_id = query_registry_value(winreg.HKEY_CLASSES_ROOT, rf'{prog_id}\Shell\open', 'PackageId')
            relative_exe_path = query_registry_value(winreg.HKEY_CLASSES_ROOT, rf'{prog_id}\Shell\open', 'PackageRelativeExecutable')
            if package_id and relative_exe_path:
                path = clean_path(fr'"C:\Program Files\WindowsApps\{package_id}\{relative_exe_path}"')
                if os.path.exists(path):
                    return path
     
        # Try to get path from HKEY_CLASSES_ROOT using directly the extension
        class_root = query_registry_value(winreg.HKEY_CLASSES_ROOT, ext, '')
        if class_root:
            path = query_registry_value(winreg.HKEY_CLASSES_ROOT, fr'{class_root}\shell\open\command', '')
            if path:
                return clean_path(path)
     
        # Try to get path from Software classes using ProgID in HKEY_LOCAL_MACHINE
        path = query_registry_value(winreg.HKEY_LOCAL_MACHINE, fr'Software\Classes\{ext}\shell\open\command', '')
        if path:
            return clean_path(path)
     
        # Try to get ProgId from OpenWithProgids in HKEY_CLASSES_ROOT
        prog_id = enum_registry_value(winreg.HKEY_CLASSES_ROOT, fr'{ext}\OpenWithProgids', 0)
        if prog_id:
            path = query_registry_value(winreg.HKEY_CLASSES_ROOT, fr'{prog_id}\shell\open\command', '')
            if path:
                return clean_path(path)
     
        # Try to get ProgId from OpenWithList in HKEY_CURRENT_USER
        prog_id = enum_registry_value(winreg.HKEY_CURRENT_USER, fr'Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{ext}\OpenWithList', 0)
        if prog_id:
            path = query_registry_value(winreg.HKEY_CLASSES_ROOT, fr'{prog_id}\shell\open\command', '')
            if path:
                return clean_path(path)
     
        # If no path is found, return None
        return None
     
    # Extensions to check (examples)
    extensions = [
        '.txt', '.xml', '.html',
        '.pdf', '.doc', '.dot', '.dotx', '.pptx', '.xlsm',
        '.jpg', '.png', '.svg', '.webp', '.gif', '.bmp',
        '.py', '.php',
        '.sys', '.bin', '.bat',
        '.rar', '.zip', '.7zip',
        '.mp4', '.avi',
        '.wav', '.mp3',
    ]
     
    for extension in extensions:
        app_path = get_app_path(extension)
        print(f'Extension: {extension}, Program: {app_path}')
    La fonction get_app_path retourne le chemin d'accès, y compris pour les Apps Microsoft
    Seul les fichiers (dans mes tests en tout cas) '.sys' et '.bin' ne retourne pas d'application (ce qui n'est pas étonnant). Les fichiers '.bat' retourne '%1', je ne sais pas trop comment l'interpréter.
    Si vous identifiez d'autres extensions qui ne donne pas le chemin d'accès mais retourne None, n'hésitez pas à m'en faire part

    Dymon

  6. #6
    Expert confirmé Avatar de papajoker
    Homme Profil pro
    Développeur Web
    Inscrit en
    Septembre 2013
    Messages
    2 321
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Nièvre (Bourgogne)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Septembre 2013
    Messages : 2 321
    Par défaut
    si tu désires d'autres extensions à tester :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    import mimetypes
    mimetypes.init()
    print(mimetypes.suffix_map.keys())
    print(mimetypes.types_map.keys())
    len(mimetypes.types_map.keys()) == 1612 sans mimetypes.init() je n'ai plus que 154 extensions
    Mais normal que ton os ne reconnait pas tout ou alors tu as installé 36 000 applications ?


    -----------------------------------

    EDIT:
    note: suis sous linux, et je peux simplement faire un :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    os.system("xdg-open " + "logo.png")
    la commande start sous win ne fait pas la même chose ???? Et ton code n'a alors pas trop d'utilité il me semble ?
    $moi= (:nono: !== :oops:) ? :king: : :triste: ;

  7. #7
    Membre confirmé
    Homme Profil pro
    Apprenti dev Python
    Inscrit en
    Août 2021
    Messages
    69
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Apprenti dev Python

    Informations forums :
    Inscription : Août 2021
    Messages : 69
    Par défaut
    Parfait, merci 👍

    Dymon

Discussions similaires

  1. Réponses: 3
    Dernier message: 27/04/2011, 15h19
  2. Créer une extension de fichier
    Par GodGives dans le forum VB 6 et antérieur
    Réponses: 10
    Dernier message: 12/11/2007, 08h44
  3. Réponses: 7
    Dernier message: 02/07/2007, 14h37
  4. Créer une variable d'environnement à partir d'une liste de fichier
    Par ddams dans le forum Shell et commandes GNU
    Réponses: 2
    Dernier message: 23/02/2007, 20h03
  5. la fonction pour connaitre une extension de fichier ?
    Par Zen_Fou dans le forum Langage
    Réponses: 6
    Dernier message: 11/05/2006, 16h30

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo