使用Python設(shè)置Windows文件默認(rè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)先使用
assoc和ftype命令行設(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)文章
Python實(shí)現(xiàn)Smtplib發(fā)送帶有各種附件的郵件實(shí)例
本篇文章主要介紹了Python實(shí)現(xiàn)Smtplib發(fā)送帶有各種附件的郵件實(shí)例,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-06-06
通過實(shí)例解析Python文件操作實(shí)現(xiàn)步驟
這篇文章主要介紹了通過實(shí)例解析Python文件操作實(shí)現(xiàn)步驟,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-09-09
Python 刪除整個文本中的空格,并實(shí)現(xiàn)按行顯示
今天小編就為大家分享一篇Python 刪除整個文本中的空格,并實(shí)現(xiàn)按行顯示,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07
使用python求解迷宮問題的三種實(shí)現(xiàn)方法
關(guān)于迷宮問題,常見會問能不能到達(dá)某點(diǎn),以及打印到達(dá)的最短路徑,下面這篇文章主要給大家介紹了關(guān)于如何使用python求解迷宮問題的三種實(shí)現(xiàn)方法,需要的朋友可以參考下2022-03-03
python?動態(tài)規(guī)劃問題解析(背包問題和最長公共子串)
這篇文章主要介紹了python?動態(tài)規(guī)劃(背包問題和最長公共子串),在動態(tài)規(guī)劃中,你要將某個指標(biāo)最大化。在這個例子中,你要找出兩個單詞的最長公共子串。fish和fosh都包含的最長子串是什么呢,感興趣的朋友跟隨小編一起看看吧2022-05-05
python爬蟲學(xué)習(xí)筆記之Beautifulsoup模塊用法詳解
這篇文章主要介紹了python爬蟲學(xué)習(xí)筆記之Beautifulsoup模塊用法,結(jié)合實(shí)例形式詳細(xì)分析了python爬蟲Beautifulsoup模塊基本功能、原理、用法及操作注意事項(xiàng),需要的朋友可以參考下2020-04-04
使用venv命令創(chuàng)建和使用python環(huán)境的詳細(xì)步驟
venv和virtualenv都是搭建虛擬環(huán)境的工具,virtualenv是第三方開源的,而venv作為virtualenv的一個子集自Python3.3開始集成到標(biāo)準(zhǔn)庫中,這篇文章主要介紹了使用venv命令創(chuàng)建和使用python環(huán)境的詳細(xì)步驟,需要的朋友可以參考下2025-12-12
python?numpy庫之如何使用matpotlib庫繪圖
Numpy的主要對象是同構(gòu)多維數(shù)組,它是一個元素表,所有類型都相同,由非負(fù)整數(shù)元組索引,在Numpy維度中稱為軸,這篇文章主要介紹了python?numpy庫?使用matpotlib庫繪圖,需要的朋友可以參考下2022-10-10

