Last active
July 30, 2019 03:00
-
-
Save Pagliacii/182a3839ecb7323cc0e041f397e72078 to your computer and use it in GitHub Desktop.
Find the default open command by file extension on Windows
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# _*_ coding:utf-8 _*_ | |
from subprocess import Popen, PIPE | |
class AssociationNotFound(Exception): | |
# means: File association not found for extension .ext | |
pass | |
class FileTypeError(Exception): | |
# means: File type 'file_type' not found or no open command associated with it. | |
pass | |
def getFileTypeByExtension(extension): | |
""" | |
use `assoc` command to get the file type by extension | |
C:\Users\root>assoc .png | |
.png=IrfanView.png | |
C:\Users\root>assoc .igs | |
File association not found for extension .igs | |
Args: | |
extension <str> file extension, like ".png" | |
Raise: | |
AssociationNotFound | |
Return: | |
result <str> file type, like "IrfanView.png" | |
""" | |
p = Popen(["assoc", extension], stdout=PIPE, stderr=PIPE, shell=True) | |
output, error = p.communicate() | |
if error: | |
raise AssociationNotFound(error) | |
return output.strip().split("=")[-1] | |
def getOpenCommandByFileType(file_type): | |
""" | |
use `ftype` command to get the open command by file type | |
C:\Users\root>ftype IrfanView.png | |
IrfanView.png="<path-to-command>\i_view32.exe" "%1" | |
C:\Users\root>ftype pngfile | |
File type 'pngfile' not found or no open command associated with it. | |
Args: | |
file_type <str> file type, like "IrfanView.png" | |
Raise: | |
FileTypeError | |
Return: | |
result <str> open command, like '"<path-to-command>\i_view32.exe" "%1"' | |
""" | |
p = Popen(["ftype", file_type], stdout=PIPE, stderr=PIPE, shell=True) | |
output, error = p.communicate() | |
if error: | |
raise FileTypeError(error) | |
return output.strip().split("=")[-1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment