macOS 开发 - AppleScript 简介

本文深入探讨AppleScript的原理和应用,包括其作为Apple事件通信(IAC)的脚本语言特性,OSA架构下的运作机制,以及如何在Cocoa应用程序中使用。同时,介绍了osascript命令的使用,Python调用AppleScript的方法,以及如何使自己的应用支持AppleScript。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Applescript


一、简述 Applescript

Applescript 是 Apple 开发根据 Apple events 来做 应用间通信(IAC : inter-application communication )的脚本语言。

在这里插入图片描述


相关语言特性

  • 面向对象
  • 采用Unicode文字编码,不区分大小写

OSA

https://www.oreilly.com/library/view/applescript-in-a/1565928415/ch01s02s01.html

The Open Scripting Architecture, which has been present on the Mac since the early 1990s, is Apple Computer’s mechanism for making interapplication communication available to a spectrum of scripting languages. AppleScript is the OSA language that Apple provides, but there are other OSA-compliant languages, including UserLand Frontier and JavaScript.[2]

OSA accomplishes this “the-more-the-merrier” approach to scripting systems by using Apple events as the unifying technology. The situation is similar to Open Database Connectivity (ODBC) on the Windows platform, where any client application can talk to different database management systems using ODBC as a common conduit (as long as ODBC driver software exists for that particular database). In terms of OSA, the conduit (on Mac OS 9) is a scripting component that can convert whatever scripting language is used (AppleScript or JavaScript) into one or more properly constructed Apple events. Figure 1-3 shows the same Apple event being sent to an application in two different scripting languages.


OSA: Open Scripting Architecture
AppleScript 是 Apple 提供的 OSA 语言;


二、编写工具

ps:系统环境:10.13.6

  • 脚本编辑器;地址位于 /Applications/Utilities/Script Editor.app
  • 自动操作; /Applications/Automator.app

在这里插入图片描述


脚本编辑器的使用


1、便捷调用命令
在这里插入图片描述


点击上方按钮,自动生成下面的代码

在这里插入图片描述


2、编写一个简单的脚本
在桌面创建文件夹
在这里插入图片描述


可以保存为以下格式
在这里插入图片描述


三、osascript 命令

osascript – execute OSA scripts (AppleScript, JavaScript, etc.)

osascript 是用来执行 OSA 脚本的(包含 AppleScript, JavaScript 等等)。

执行地址: /usr/bin/osascript

方法选项:osascript [-l language] [-i] [-s flags] [-e statement | programfile] [argument ...]


osascript 使用举例

  • 运行一句脚本:
osascript -e 'display dialog "hello world"'
  • 运行脚本文件:
osascript PATH-TO-SCRIPT.scpt

其他相关命令

  • osalang
  • osacompile

四、Cocoa 相关类

  • NSAppleScript
  • NSAppleEventDescriptor

使用 NSAppleScript

在 AuthorizationExecuteWithPrivileges 方法过期的情况下,用 NSAppleScript 执行高权限命令是一个不错的方法:

+ (AppleScriptReturn *)runAppleScript:(NSString *)command previledged:(BOOL)previledged{
    
    NSString *script = [NSString stringWithFormat:@"do shell script \"%@\"", command];
    if (previledged) {
        script = [script stringByAppendingString:@" with administrator privileges"];
    }
    
    NSAppleScript *appleScript = [[NSAppleScript new] initWithSource:script];
    
    NSDictionary *scriptError = [NSDictionary new];
    
    
    NSAppleEventDescriptor *descriptor = [appleScript executeAndReturnError:&scriptError];
    
    NSLog(@"runAppleScript : %@ , scriptError : %@",descriptor.stringValue,scriptError);
    
    AppleScriptReturn *returnModel = [[AppleScriptReturn alloc]init];
    
    if(scriptError.allKeys.count > 0) {
        
        returnModel.ret = NO;
        returnModel.result = [scriptError objectForKey:NSAppleScriptErrorMessage];
        
    } else {
        
        NSAppleEventDescriptor *unicode = [descriptor coerceToDescriptorType:typeUnicodeText];
        NSData *data = [unicode data];
        NSString *result = [[NSString alloc] initWithCharacters:(unichar*)[data bytes] length:[data length] / sizeof(unichar)];
        
        returnModel.ret = YES;
        returnModel.result = result;
        
    }
    
    NSLog(@"%d - %@",returnModel.ret,returnModel.result);
    
    return returnModel;
}


五、查看应用对 Applescript 的支持

在这里插入图片描述


在这里插入图片描述


在这里插入图片描述


在这里插入图片描述



六、让自己的应用支持 Applescript

– Applescript support to my Cocoa application?
https://stackoverflow.com/questions/2479585/how-do-i-add-applescript-support-to-my-cocoa-application


七、Python 调用 Applescript

使用库 applescript
PYPI : https://pypi.org/project/applescript/

import applescript
r = applescript.run('return 1')

# 运行脚本
r = applescript.run('path/to/file.applescript')

# 打开终端运行脚本
applescript.tell.app("Terminal",'do script "ls"')

# 后台运行脚本
applescript.tell.app("Terminal",'do script "ls"',background=True)


# 运行多个组合脚本
command="cd ~/Downloads/figures && srcana && ls"
applescript.tell.app("Terminal",f'''do script "{command}"''')

八、一些编写示例


在 Safari 新窗口中打开网页

tell application "Safari"
	tell window 1
		set current tab to (make new tab with properties {URL:"https://blog.csdn.net/lovechris00/"})
	end tell
end tell

将当前 safari 页面切换为指定页面

tell application "Safari" to set the URL of the front document to "https://blog.csdn.net/lovechris00/"

通过终端执行命令 echo ‘hello’

tell application "Terminal"
    do shell script "echo 'hello' " 
end tell

打开终端执行python文件
在 python 中调用

python_path = '~/opt/anaconda3/bin/python3.7'
script_path = '~/code/detail.py'
s1 = f'''
    tell application "Terminal" 
        set newTab to do script "{python_path} {script_path} 00 " 
    end tell
'''
ret = applescript.run(s1)

参考



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程乐园

请我喝杯伯爵奶茶~!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值