AppleScript读取环境变量CJK字符异常,求修复方案
修复AppleScript读取UTF-8环境变量乱码的问题
这个问题的核心原因很明确:AppleScript的system attribute命令默认使用MacRoman编码读取环境变量,而我们日常用的UTF-8编码内容在MacRoman解码下就会变成乱码。下面给你几个实用的修复方案:
方案1:手动转码(兼容所有场景)
利用AppleScript可以桥接Objective-C的特性,把system attribute拿到的MacRoman编码字符串转换成UTF-8:
-- 获取原始的MacRoman编码值 set rawHello to system attribute "HELLO" -- 转码为UTF-8字符串 set utf8Hello to current application's NSString's stringWithString:rawHello ¬ |encoding|:(current application's NSMacOSRomanStringEncoding) ¬ 's stringUsingEncoding:(current application's NSUTF8StringEncoding) -- 验证输出 do shell script "echo " & utf8Hello
执行这个脚本时,只要环境变量HELLO=你好已正确设置,就能输出正常的「你好」。
方案2:直接通过Shell读取环境变量(更简洁)
既然do shell script默认和Shell用UTF-8交互,我们可以跳过system attribute,直接在Shell命令里读取环境变量:
set helloValue to do shell script "echo $HELLO" do shell script "echo " & helloValue
注意:如果是在终端里临时设置环境变量,要确保变量能传递给osascript进程,比如用一行命令执行:
HELLO=你好 osascript -e 'set helloValue to do shell script "echo $HELLO"; do shell script "echo " & helloValue'
如果是先export HELLO=你好再执行脚本,也要确保是在同一个Shell会话中。
为什么原命令会乱码?
你之前的测试里,直接在do shell script里写中文能正常输出,是因为AppleScript会把字符串自动转成UTF-8传递给Shell;但system attribute是从系统环境变量里读取原始字节,然后用MacRoman解码成字符串,这就导致UTF-8的「你好」字节被错误解析,出现乱码「‰Ω†Â•Ω」。
内容的提问来源于stack exchange,提问作者Meow
相关产品推荐
相关产品推荐

