OSX的剪贴板转储机

时间:2013-08-04 03:54:51

标签: macos applescript clipboard

我想在applescript中制作一个小应用程序,用于轮询剪贴板中的更改,并在检测到任何内容后,将剪贴板的内容转储到文本文件中。这是我提出的代码,它创建了文件但没有任何内容写入其中。我做错了什么?

property oldvalue : missing value

on idle
    local newValue
    set newValue to the clipboard
    if oldvalue is not equal to newValue then
        try
            tell application "Finder"
                try
                    set the_file to "/Users/xxx/Documents/dump2.txt" as POSIX file as alias
                on error
                    set the_file to (make new document file at ("/Users/xxx/Documents/" as POSIX file as alias) with properties {name:"dump2", text:""})
                end try
            end tell

            try
                open for access the_file with write permission
                write newValue to file the_file starting at eof
                close access the_file
            on error
                try
                    close access the_file
                end try
            end try

        end try

        set oldvalue to newValue

    end if

    return 1 
end idle

1 个答案:

答案 0 :(得分:1)

open for access也接受POSIX路径作为参数的文本,并且指定为参数的路径不必存在。您的脚本无效,因为make new document file返回Finder文件对象,而as POSIX file as alias部分始终导致错误。

property old : ""
on idle
    set new to the clipboard
    if new is not old then
        set old to new
        if new does not end with linefeed then set new to new & linefeed
        set b to open for access "/tmp/clipboard.txt" with write permission
        write new to b as «class utf8» starting at eof
        close access b
    end if
    return 1
end idle

as «class utf8»是必需的,因为默认情况下write仍然使用主编码(如MacRoman或MacJapanese)。 as Unicode text将是UTF-16。