파이썬(Python) 코드로 윈도우(Windows), 맥OS(macOS) 폰트 설치하기

VDoring·2023년 2월 9일
0

Python

목록 보기
3/4
post-thumbnail

파이썬 코드로 폰트(.ttf .otf)를 설치하는 방법을 알려드리겠습니다.

이 부분은 제가 프로그램을 만들면서 꽤나 고민한 부분이니, 잘 봐주시면 감사하겠습니다.

아래의 코드가 작동하려면 "관리자 권한"이 필요합니다. 이걸 잊으시면 안됩니다.


윈도우의 경우, 이렇게 2가지 방법이 있습니다.

Windows 폰트 설치 방법 1번째

import os
import winreg


def install_font(font_file_path):
    # Open the registry key where the font information is stored
    key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts", 0,
                         winreg.KEY_ALL_ACCESS)

    # Get the name of the font file
    font_file_name = os.path.basename(font_file_path)

    # Set the font information in the registry
    winreg.SetValueEx(key, font_file_name, 0, winreg.REG_SZ, font_file_path)

    # Close the registry key
    winreg.CloseKey(key)


# Example usage
font_file_path = "C:\Windows\Fonts\myfont.ttf"
install_font(font_file_path)

Windows 폰트 설치 방법 2번째

import ctypes

def install_font(font_path):
    # Load the AddFontResourceA function from the gdi32 library
    addfont = ctypes.windll.gdi32.AddFontResourceA

    # Call the AddFontResourceA function with the font path as the argument
    result = addfont(font_path)

    # Return True if the font was installed successfully, False otherwise
    return result != 0

# Example usage
font_path = r"C:\Windows\Fonts\myfont.ttf"
result = install_font(font_path)

if result:
    print("Font installed successfully")
else:
    print("Font installation failed")

폰트 파일을 모든 사용자용이나 현재 사용자용으로 옮긴 뒤, 레지스트리를 등록하는 방법입니다.


다음으로 macOS입니다.

맥OS의 경우에도, 이렇게 2가지 방법이 있습니다.

macOS 폰트 설치 방법 1번째

import subprocess
import os

# Path to the font file
font_path = "/path/to/font.ttf"

# The command to install the font
command = "cp " + font_path + " /Library/Fonts/"

# Use the subprocess module to run the command in terminal
subprocess.call(['sudo', '-s', command])

macOS 폰트 설치 방법 2번째

import subprocess

def install_font(font_path):
    # Use the cp command to copy the font to the Fonts directory
    result = subprocess.run(["cp", font_path, "/Library/Fonts/"])

    # Return True if the font was installed successfully, False otherwise
    return result.returncode == 0

# Example usage
font_path = "/path/to/myfont.ttf"
result = install_font(font_path)

if result:
    print("Font installed successfully")
else:
    print("Font installation failed")
profile
< Beginners Heart >

0개의 댓글