PythonでWindowsファイルのデフォルトアプリケーションを設定する方法

公開日: 2026-01-20 01:00 更新日: 2026-01-20 12:00 936文字 5 min read

このコードは、Windows システム設定ファイルのデフォルトで開くアプリケーションを変更するための Python ツールです。コマンドラインとレジストリの2つの方法で関連付けを変更でき、Windows 7/10/11 にも対応しています。

AIモデル Qwen/Qwen3-8B による翻訳。

原文言語:Simplified Chinese、翻訳先言語:japanese、翻訳時間:2026-05-01 04:32

AI 翻訳は参考に限り、内容の完全な正確性を保証できません。原文をご参照ください。

前言

本人はクラスで任命された電教委員(苦労な仕事)である。クラスの教育的なニーズのために、特定の日付に特定のプレイヤーを使用する必要があった。

本人はPythonを用いてMP4ファイルのデフォルト開くアプリケーションを自動化設定しようと試みたが、deepseekなどのアシスタントに生成してもらったコードを実行したところ、さまざまな不具合で詰まってしまった。やむを得ずGitHubで関連するコードを探したところ、本当にPythonで書かれた「ファイルのデフォルトアプリケーション設定ソフト」を見つけた。原作者に感謝したい。

https://github.com/3089464667/default-app

このコードを読み、デフォルトアプリケーション設定の核心となるコードを抽出した。

コードの説明

このコードは、Windowsシステムでファイルのデフォルト開くアプリケーションを設定するためのPythonツールである。システムの関連付けを変更するため、コマンドラインとレジストリの両方で処理が行われ、Windows 7/10/11すべてのバージョンに対応している。

核心機能

  • デフォルトアプリケーションの設定set_default_app()関数を使用して、ファイル拡張子と対応するアプリケーションのパスを指定し、システムの関連付けを自動で設定できる。
  • 互換性処理assocftypeコマンドラインによる設定を優先し、同時にレジストリを直接編集し、Windows 10/11のユーザー選択検証メカニズムを処理する。
  • 検証機能check_default_app()は現在のデフォルトアプリケーションが指定したアプリであるかを確認する。

使用例

set_default_app(".txt", "C:\\Windows\\notepad.exe")
if check_default_app(".txt", "C:\\Windows\\notepad.exe"):
    print("设置成功")

完整コード

import winreg
import subprocess
import os
import time
import hashlib

def set_default_app_cmd(file_extension, app_path):
    """
    使用 Windows 命令行工具设置默认打开程序,兼容 Windows 10/11
    """
    try:
        ext = file_extension if file_extension.startswith('.') else '.' + file_extension
        prog_id = ext[1:].upper() + "File"
        subprocess.run(f'assoc {ext}={prog_id}', shell=True, check=True)
        subprocess.run(f'ftype {prog_id}="{app_path}" "%1"', shell=True, check=True)
        return True, ""
    except Exception as e:
        return False, str(e)

def set_default_app(file_extension, app_path, icon_path=None):
    """
    设置文件扩展名的默认打开程序
    参数:
        file_extension: 文件扩展名(如 ".txt" 或 "txt")
        app_path: 应用程序完整路径
        icon_path: 可选图标路径
    返回: 无
    """
    # 先用命令行设置
    ok, msg = set_default_app_cmd(file_extension, app_path)
    if not ok:
        print(f"命令行设置失败: {msg}")
    
    try:
        # 确保扩展名格式正确
        ext = file_extension if file_extension.startswith('.') else '.' + file_extension
        
        # 创建或打开扩展名对应的注册表键
        with winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, ext) as key:
            prog_id = winreg.QueryValue(key, None)
            if not prog_id:
                prog_id = ext[1:].upper() + "File"
                winreg.SetValue(key, None, winreg.REG_SZ, prog_id)
            
            # 设置打开命令
            with winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, f"{prog_id}\\shell\\open\\command") as cmd_key:
                winreg.SetValue(cmd_key, None, winreg.REG_SZ, f"\"{app_path}\" \"%1\"")
        
        # 处理用户选择(Windows 10/11 需要)
        user_choice_path = f"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\{ext}\\"
        try:
            with winreg.OpenKey(winreg.HKEY_CURRENT_USER, user_choice_path, 0, winreg.KEY_ALL_ACCESS) as key:
                winreg.DeleteKey(key, "UserChoice")
        except WindowsError:
            pass
        
        # 生成用户选择哈希(Windows 10/11 验证机制)
        try:
            user_sid = os.getlogin()
        except Exception:
            user_sid = "unknown"
        
        timestamp = int(time.time())
        hash_input = f"{prog_id}{user_sid}{timestamp}".encode('utf-16le')
        hash_value = hashlib.sha256(hash_input).hexdigest()
        
        with winreg.CreateKey(winreg.HKEY_CURRENT_USER, user_choice_path + "UserChoice") as key:
            winreg.SetValueEx(key, "ProgId", 0, winreg.REG_SZ, prog_id)
            winreg.SetValueEx(key, "Hash", 0, winreg.REG_SZ, hash_value)
        
        print(f"成功设置 {ext} 的默认打开程序为: {app_path}")
        
    except Exception as e:
        print(f"设置默认程序失败: {e}")

def check_default_app(file_extension, app_path):
    """
    检查当前扩展名的默认打开程序是否为指定程序
    参数:
        file_extension: 文件扩展名
        app_path: 应用程序路径
    返回: True/False
    """
    ext = file_extension if file_extension.startswith('.') else '.' + file_extension
    try:
        output = subprocess.check_output(f"assoc {ext}", shell=True, encoding="gbk", errors="ignore")
        if "=" not in output:
            return False
        prog_id = output.strip().split("=")[-1]
        output2 = subprocess.check_output(f"ftype {prog_id}", shell=True, encoding="gbk", errors="ignore")
        if app_path.lower() in output2.lower():
            return True
    except Exception:
        pass
    return False

# 使用示例
if __name__ == "__main__":
    # 示例1:设置.txt文件用记事本打开
    set_default_app(".txt", "C:\\Windows\\notepad.exe")
    
    # 示例2:设置.jpg文件用照片查看器打开
    set_default_app("jpg", "C:\\Windows\\System32\\rundll32.exe", "C:\\Windows\\System32\\photo_viewer.dll")
    
    # 检查设置是否成功
    if check_default_app(".txt", "C:\\Windows\\notepad.exe"):
        print("设置成功!")
    else:
        print("设置失败!")

気に入ったならばコメントを残してくださいね~