Python脚本如何适配Mac系统

wen python案例 24

本文目录导读:

Python脚本如何适配Mac系统

  1. 系统环境配置
  2. 路径适配
  3. 权限处理
  4. 系统API调用
  5. 依赖管理
  6. 打包为Mac应用
  7. 常见问题处理
  8. 完整示例
  9. 调试技巧
  10. 注意事项

在Mac系统上适配Python脚本主要需要考虑以下几点:

系统环境配置

安装Python

# 使用Homebrew安装
brew install python3
# 或从官网下载:https://www.python.org/downloads/

检查Python版本

python3 --version
which python3

路径适配

处理文件路径

import os
import platform
# 获取Mac用户目录
home = os.path.expanduser("~")
# 跨平台路径处理
from pathlib import Path
data_path = Path.home() / "Documents" / "data"
# 使用os.path.join确保跨平台兼容
file_path = os.path.join(home, "Library", "Application Support", "myapp")

Mac特有路径

# 应用程序支持目录
app_support = os.path.expanduser("~/Library/Application Support")
# 临时目录
import tempfile
temp_dir = tempfile.gettempdir()
# 资源目录(针对.app包)
import sys
if getattr(sys, 'frozen', False):
    # 打包后的应用
    base_path = sys._MEIPASS
else:
    base_path = os.path.dirname(os.path.abspath(__file__))

权限处理

请求系统权限

import subprocess
def request_accessibility_permission():
    """请求辅助功能权限"""
    script = '''
    tell application "System Events"
        activate
    end tell
    '''
    subprocess.run(['osascript', '-e', script])
# 检查是否有权限
def check_permissions():
    try:
        # 尝试访问受保护资源
        subprocess.run(['osascript', '-e', 'return 1'], check=True, capture_output=True)
        return True
    except subprocess.CalledProcessError:
        return False

系统API调用

使用AppleScript

import subprocess
# 显示通知
def show_notification(title, message):
    script = f'''
    display notification "{message}" with title "{title}"
    '''
    subprocess.run(['osascript', '-e', script])
# 获取系统信息
def get_system_info():
    script = '''
    set osVersion to system version of (system info)
    set computerName to computer name of (system info)
    return osVersion & "|" & computerName
    '''
    result = subprocess.run(['osascript', '-e', script], capture_output=True, text=True)
    return result.stdout.strip().split("|")

使用Foundation框架

import objc
from Foundation import NSBundle
# 获取应用信息
bundle = NSBundle.mainBundle()
app_name = bundle.objectForInfoDictionaryKey_("CFBundleName")

依赖管理

requirements.txt示例

# Mac特定依赖
pyobjc-framework-Cocoa>=9.0  # macOS API绑定
py2app>=0.28                  # 打包为.app
# 跨平台依赖
requests>=2.31.0
Pillow>=10.0.0

条件导入

import platform
if platform.system() == 'Darwin':
    try:
        import Quartz
        MACOS_AVAILABLE = True
    except ImportError:
        MACOS_AVAILABLE = False
else:
    MACOS_AVAILABLE = False

打包为Mac应用

使用py2app

# setup.py
from setuptools import setup
APP = ['your_script.py']
DATA_FILES = []
OPTIONS = {
    'argv_emulation': True,
    'iconfile': 'app.icns',
    'plist': {
        'CFBundleShortVersionString': '1.0.0',
        'CFBundleIdentifier': 'com.yourcompany.yourapp',
        'NSHighResolutionCapable': True,
    }
}
setup(
    app=APP,
    data_files=DATA_FILES,
    options={'py2app': OPTIONS},
    setup_requires=['py2app'],
)
# 打包命令
python setup.py py2app

常见问题处理

处理编码问题

import sys
import locale
# 设置正确的编码
if sys.platform == 'darwin':
    # Mac默认使用UTF-8
    sys.setdefaultencoding('utf-8')  # Python 2
    # Python 3默认就是UTF-8

处理文件对话框

import subprocess
import json
def open_file_dialog():
    """使用AppleScript打开文件选择对话框"""
    script = '''
    set filePath to choose file
    return POSIX path of filePath
    '''
    result = subprocess.run(['osascript', '-e', script], 
                          capture_output=True, text=True)
    return result.stdout.strip() if result.returncode == 0 else None

完整示例

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import platform
import subprocess
from pathlib import Path
class MacAdapter:
    """Mac系统适配器"""
    def __init__(self):
        self.is_mac = platform.system() == 'Darwin'
    def get_app_support_dir(self, app_name):
        """获取应用支持目录"""
        if self.is_mac:
            support_dir = Path.home() / "Library" / "Application Support" / app_name
        else:
            # Linux/Windows备选
            support_dir = Path.home() / ".config" / app_name
        support_dir.mkdir(parents=True, exist_ok=True)
        return support_dir
    def show_os_notification(self, title, message):
        """跨平台通知"""
        if self.is_mac:
            script = f'display notification "{message}" with title "{title}"'
            subprocess.run(['osascript', '-e', script])
        else:
            print(f"[{title}] {message}")
    def get_default_font_path(self):
        """获取Mac系统字体路径"""
        if self.is_mac:
            return "/System/Library/Fonts/Helvetica.ttc"
        return None
# 使用示例
if __name__ == "__main__":
    adapter = MacAdapter()
    # 检查系统
    print(f"运行在Mac系统: {adapter.is_mac}")
    # 获取应用目录
    data_dir = adapter.get_app_support_dir("MyPythonApp")
    print(f"数据目录: {data_dir}")
    # 发送通知
    adapter.show_os_notification("提示", "Python脚本已启动")

调试技巧

# 查看Python路径
which python3
# 检查环境变量
echo $PATH
# 查看系统版本
sw_vers
# 查看Python架构
python3 -c "import platform; print(platform.machine())"

注意事项

  1. Apple Silicon兼容性:确保使用arm64版本的Python
  2. 安全设置:macOS有严格的沙盒和权限控制
  3. 文件系统:macOS大小写不敏感但保留大小写
  4. GUI框架:推荐使用Tkinter(系统自带)或PyQt

抱歉,评论功能暂时关闭!