Skip to content

Instantly share code, notes, and snippets.

@Pagliacii
Last active July 30, 2019 03:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pagliacii/182a3839ecb7323cc0e041f397e72078 to your computer and use it in GitHub Desktop.
Save Pagliacii/182a3839ecb7323cc0e041f397e72078 to your computer and use it in GitHub Desktop.
Find the default open command by file extension on Windows
# _*_ 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