最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用Python設(shè)置Windows文件默認(rèn)打開程序

 更新時間:2026年01月21日 08:41:22   作者:用戶836279132519  
本文介紹了一個用于Windows系統(tǒng)設(shè)置文件默認(rèn)打開程序的Python工具,通過命令行和注冊表兩種方式修改關(guān)聯(lián),適用于Windows7/10/11,代碼包括設(shè)置默認(rèn)程序、兼容性處理和驗(yàn)證功能,并提供了使用示例,需要的朋友可以參考下

前言

本人為班里任命的電教委員(苦差事),因班里的教學(xué)需求,要在特定的某天切換使用某個播放器。

本人就想通過 Python 自動化設(shè)置默認(rèn) MP4 打開程序,然后就在請教 deepseek 等助手后,運(yùn)行其生成的代碼。隨后就被各種奇怪的報錯給卡死了。無奈之下便上 Github 看看有沒有相關(guān)的代碼。

代碼講解

這段代碼是一個用于 Windows 系統(tǒng)設(shè)置文件默認(rèn)打開程序的 Python 工具。它通過命令行和注冊表兩種方式修改關(guān)聯(lián),適用于 Windows 7/10/11。

核心功能

  • 設(shè)置默認(rèn)程序:通過 set_default_app() 函數(shù)指定文件擴(kuò)展名與對應(yīng)的應(yīng)用程序路徑,可自動配置系統(tǒng)關(guān)聯(lián)。
  • 兼容性處理:優(yōu)先使用 assocftype 命令行設(shè)置,同時直接修改注冊表,并處理 Windows 10/11 的用戶選擇驗(yàn)證機(jī)制。
  • 驗(yàn)證功能check_default_app() 可檢查當(dāng)前默認(rèn)程序是否為指定應(yīng)用。

使用示例

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

完整代碼

import winreg
import subprocess
import os
import time
import hashlib

def set_default_app_cmd(file_extension, app_path):
    """
    使用 Windows 命令行工具設(shè)置默認(rèn)打開程序,兼容 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):
    """
    設(shè)置文件擴(kuò)展名的默認(rèn)打開程序
    參數(shù):
        file_extension: 文件擴(kuò)展名(如 ".txt" 或 "txt")
        app_path: 應(yīng)用程序完整路徑
        icon_path: 可選圖標(biāo)路徑
    返回: 無
    """
    # 先用命令行設(shè)置
    ok, msg = set_default_app_cmd(file_extension, app_path)
    if not ok:
        print(f"命令行設(shè)置失敗: {msg}")
    
    try:
        # 確保擴(kuò)展名格式正確
        ext = file_extension if file_extension.startswith('.') else '.' + file_extension
        
        # 創(chuàng)建或打開擴(kuò)展名對應(yīng)的注冊表鍵
        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)
            
            # 設(shè)置打開命令
            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 驗(yàn)證機(jī)制)
        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"成功設(shè)置 {ext} 的默認(rèn)打開程序?yàn)? {app_path}")
        
    except Exception as e:
        print(f"設(shè)置默認(rèn)程序失敗: {e}")

def check_default_app(file_extension, app_path):
    """
    檢查當(dāng)前擴(kuò)展名的默認(rèn)打開程序是否為指定程序
    參數(shù):
        file_extension: 文件擴(kuò)展名
        app_path: 應(yīng)用程序路徑
    返回: 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:設(shè)置.txt文件用記事本打開
    set_default_app(".txt", "C:\\Windows\\notepad.exe")
    
    # 示例2:設(shè)置.jpg文件用照片查看器打開
    set_default_app("jpg", "C:\\Windows\\System32\\rundll32.exe", "C:\\Windows\\System32\\photo_viewer.dll")
    
    # 檢查設(shè)置是否成功
    if check_default_app(".txt", "C:\\Windows\\notepad.exe"):
        print("設(shè)置成功!")
    else:
        print("設(shè)置失?。?)

到此這篇關(guān)于使用Python設(shè)置Windows文件默認(rèn)打開程序的文章就介紹到這了,更多相關(guān)Python Windows文件默認(rèn)打開內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

都兰县| 新平| 阳高县| 湖北省| 大宁县| 偏关县| 昌图县| 图木舒克市| 乡宁县| 乐东| 阳城县| 鄂托克旗| 万全县| 师宗县| 凤阳县| 江源县| 洛扎县| 南平市| 大宁县| 邵东县| 长岭县| 大埔县| 泰兴市| 左贡县| 鄂伦春自治旗| 信丰县| 邯郸市| 济阳县| 潜山县| 札达县| 淮阳县| 托克逊县| 东港市| 清涧县| 博野县| 渑池县| 剑河县| 琼中| 桦川县| 浠水县| 昌都县|