Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the default application mapped to a file extention in windows using Python

I would like to query Windows using a file extension as a parameter (e.g. ".jpg") and be returned the path of whatever app windows has configured as the default application for this file type.

Ideally the solution would look something like this:

from stackoverflow import get_default_windows_app

default_app = get_default_windows_app(".jpg")

print(default_app)
"c:\path\to\default\application\application.exe"

I have been investigating the winreg builtin library which holds the registry infomation for windows but I'm having trouble understanding its structure and the documentation is quite complex.

I'm running Windows 10 and Python 3.6.

Does anyone have any ideas to help?

like image 717
user3535074 Avatar asked Jan 01 '18 17:01

user3535074


People also ask

How do I know the extension of a file in Python?

We can use Python os module splitext() function to get the file extension. This function splits the file path into a tuple having two values - root and extension.

How do you add a file extension in Python?

Method 1: Using Python os module splittext() function This function splittext() splits the file path string into the file name and file extension into a pair of root and extension such that when both are added then we can retrieve the file path again (file_name + extension = path).


1 Answers

The registry isn't a simple well-structured database. The Windows shell executor has some pretty complex logic to it. But for the simple cases, this should do the trick:

import shlex
import winreg

def get_default_windows_app(suffix):
    class_root = winreg.QueryValue(winreg.HKEY_CLASSES_ROOT, suffix)
    with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r'{}\shell\open\command'.format(class_root)) as key:
        command = winreg.QueryValueEx(key, '')[0]
        return shlex.split(command)[0]

>>> get_default_windows_app('.pptx')
'C:\\Program Files\\Microsoft Office 15\\Root\\Office15\\POWERPNT.EXE'

Though some error handling should definitely be added too.

like image 115
Hetzroni Avatar answered Sep 23 '22 02:09

Hetzroni