You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows下以管理员运行程序仍无法复制.ttf字体到Fonts文件夹求助

问题

我尝试通过代码将.ttf字体文件安装到电脑中供程序使用,计划将该文件复制到C:/Windows/Fonts文件夹。为此我使用PyUAC获取了管理员权限,但仍出现错误:[Errno 13] Permission denied: 'C:\Windows\Fonts'。断点确认程序确实已获得管理员权限,代码如下:

import pyuac
if pyuac.isUserAdmin() == False:
    try:
        pyuac.runAsAdmin()
        INITIALIZEFONT()
    except: #用户拒绝管理员权限
        pass
else: #pyuac.isUserAdmin() == True:
    INITIALIZEFONT()
from shutil import copyfile
def INITIALIZEFONT():
    try:
        fontPath = 'C:\\myPath\\Copperplate.ttf'
        copyfile(fontPath, 'C:\\Windows\\Fonts')
    except Exception as err:
        print(err)
        breakpoint()
        input()

调试信息:

[Errno 13] Permission denied: 'C:\\Windows\\Fonts'
> c:/MYPATHHERE.py(19)INITIALIZEFONT()
-> input()
(Pdb) pyuac.isUserAdmin()
True
(Pdb)

注:此问题并非重复提问,原问题仅涉及移动文件方法,而非权限问题。请问该如何解决,或此操作是否不可行?


解决方案
  • 错误核心原因:shutil.copyfile要求目标路径必须包含完整文件名,你仅指定了文件夹C:\Windows\Fonts,系统无法识别目标文件的具体名称,即便有管理员权限也会触发混淆的权限报错(实际是参数格式错误)。
  • 修正复制逻辑:修改copyfile的目标路径,补充字体文件名:
from shutil import copyfile
def INITIALIZEFONT():
    try:
        fontPath = 'C:\\myPath\\Copperplate.ttf'
        # 目标路径必须包含完整文件名
        targetPath = 'C:\\Windows\\Fonts\\Copperplate.ttf'
        copyfile(fontPath, targetPath)
    except Exception as err:
        print(err)
        breakpoint()
        input()
  • 系统字体注册补充:仅复制文件到Fonts文件夹无法让系统全局识别该字体,需调用Windows API完成注册:
import ctypes
from shutil import copyfile

def INITIALIZEFONT():
    try:
        fontPath = 'C:\\myPath\\Copperplate.ttf'
        targetPath = 'C:\\Windows\\Fonts\\Copperplate.ttf'
        copyfile(fontPath, targetPath)
        
        # 注册字体到系统
        ctypes.windll.gdi32.AddFontResourceW(targetPath)
        # 发送通知让系统更新字体缓存
        ctypes.windll.user32.SendMessageW(0xFFFF, 0x001D, 0, 0)
    except Exception as err:
        print(err)
        breakpoint()
        input()
  • 权限获取逻辑修正:原代码中pyuac.runAsAdmin()会启动新的管理员进程,但原进程的INITIALIZEFONT()不会在新进程中执行,导致实际执行逻辑仍为普通权限。修正后的权限判断代码:
import pyuac
import sys

def main():
    INITIALIZEFONT()

if __name__ == "__main__":
    if not pyuac.isUserAdmin():
        try:
            # 启动新的管理员进程运行当前脚本
            pyuac.runAsAdmin(sys.argv[0])
        except:
            pass
    else:
        main()

内容的提问来源于stack exchange,提问作者mwolfe 11

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 07:33:14