0

我正在尝试创建我的计算机何时关闭和打开的日志。为此,我正在编写一个在启动时运行的脚本,该脚本将写入文本文件,但它告诉我我没有写入文件的权限。

使用打印语句,我确定 try 块在第一行之后终止。

writeTextToFile(getTimeInHoursAndMinutes(), "Users/labspecialist/Desktop/system_log")

on writeTextToFile(theText, theFile)
    try

        -- Convert the file to a string
        set theFile to theFile as string

        -- Open the file for writing
        set theOpenedFile to (open for access file theFile with write permission)   

        -- Write the new content to the file
        write theText to theOpenedFile starting at eof

        -- Close the file
        close access theOpenedFile

        -- Return a boolean indicating that writing was successful
        return true

        -- Handle a write error
    on error

        -- Close the file
        try
            close access file theFile
        end try

        -- Return a boolean indicating that writing failed
        return false
    end try
end writeTextToFile



on getTimeInHoursAndMinutes()
    -- Get the "hour"
    set timeStr to time string of (current date)
    set Pos to offset of ":" in timeStr
    set theHour to characters 1 thru (Pos - 1) of timeStr as string
    set timeStr to characters (Pos + 1) through end of timeStr as string

    -- Get the "minute"
    set Pos to offset of ":" in timeStr
    set theMin to characters 1 thru (Pos - 1) of timeStr as string
    set timeStr to characters (Pos + 1) through end of timeStr as string

    --Get "AM or PM"
    set Pos to offset of " " in timeStr
    set theSfx to characters (Pos + 1) through end of timeStr as string

    return (theHour & ":" & theMin & " " & theSfx) as string
end getTimeInHoursAndMinutes

我希望当我运行它时得到一个 true 的输出并且我的文件包含当前时间的新行。但是,它当前返回 false 并且没有写入文件。

4

1 回答 1

0

问题是您的脚本file在该open for access行中使用了说明符,它应该使用POSIX file说明符(因为您正在为命令提供 POSIX 路径)。它应该如下所示:

writeTextToFile(getTimeInHoursAndMinutes(), "/Users/labspecialist/Desktop/system_log")

on writeTextToFile(theText, theFile)
    try

        -- Convert the file to a string
        set theFile to theFile as string

        -- Open the file for writing
        set theOpenedFile to (open for access POSIX file theFile with write permission)

        -- Write the new content to the file
        write theText to theOpenedFile starting at eof

        -- Close the file
        close access theOpenedFile

        -- Return a boolean indicating that writing was successful
        return true

        -- Handle a write error
    on error errstr
        display dialog errstr
        -- Close the file
        try
            close access file theFile
        end try

        -- Return a boolean indicating that writing failed
        return false
    end try
end writeTextToFile

Ps 是的,你真的应该在文件路径中使用那个斜杠,尽管它似乎无论如何都可以工作......

于 2019-09-09T20:41:51.630 回答