使用苹果脚本以指定的 cpu% 退出应用程序

using apple script to exit app at a specified cpu%

我想要一个在完成文件处理后退出应用程序的脚本。下面的代码是我尝试通过研究其他创作来自己创建的代码,但未能真正让它发挥作用。这个特定的软件不支持自动化工作流程,因此我能找到的唯一触发因素是 cpu%,因为它在使用时可以使用高达 100%,在空闲时可以低至 1.3%,

getProcessPercentCPU("Mixed In Key 8")
set someProcess to getProcessPercentCPU("Mixed In Key 8")
on getProcessPercentCPU(someProcess)

repeat

    do shell script "/bin/ps -xco %cpu,command | /usr/bin/awk '/" & someProcess & "$/ {print }'"

    if someProcess is less than "2.0" then
        application "Mixed In Key 8" quit
    end if
end repeat
end getProcessPercentCPU

如果有人可以帮助我让它工作或有任何建议,我将不胜感激。我也是 applescripting 的新手。

你已经基本正确了,但看起来你在验证这些部分是否正常工作之前试图跳过。如果您将处理程序和变量命名为它们正在尝试执行的操作,它也可能会有所帮助。例如,在这种情况下,您的处理程序似乎正在监视一个应用程序,然后在该应用程序达到低 CPU 使用率后退出该应用程序。

请注意,我已将示例中的进程名称更改为 TaskPaper,因为我有可用的名称。

quitOnLowCPU("TaskPaper")

on quitOnLowCPU(processToMonitor)
    set processCPU to do shell script "/bin/ps -xco %cpu,command | /usr/bin/awk '/" & processToMonitor & "$/ {print }'"
    display dialog processCPU
end quitOnLowCPU

此时,我们知道两件事:shell 脚本返回我们想要的数字,并且它以字符串形式返回它。

为了可靠地比较数字,我们需要将它们转换为数值。

quitOnLowCPU("TaskPaper")

on quitOnLowCPU(processToMonitor)
    set processCPU to do shell script "/bin/ps -xco %cpu,command | /usr/bin/awk '/" & processToMonitor & "$/ {print }'"

    --convert the shell script response string to a number
    set processCPU to processCPU as number
    --compare to the threshold of quitting
    if processCPU is less than 2.0 then
        tell application processToMonitor to quit
    end if
end quitOnLowCPU

这有效,但它也会尝试退出 processToMonitor,即使 processToMonitor 不是 运行。

quitOnLowCPU("TaskPaper")

on quitOnLowCPU(processToMonitor)
    set processCPU to do shell script "/bin/ps -xco %cpu,command | /usr/bin/awk '/" & processToMonitor & "$/ {print }'"

    if processCPU is "" then
        --the process is gone. We're done
        return
    end if

    --convert the shell script response string to a number
    set processCPU to processCPU as number
    --compare to the threshold of quitting
    if processCPU is less than 2.0 then
        tell application processToMonitor to quit
    end if
end quitOnLowCPU

现在我们准备在处理程序周围添加 repeat

quitOnLowCPU("TaskPaper")

on quitOnLowCPU(processToMonitor)
    repeat
        set processCPU to do shell script "/bin/ps -xco %cpu,command | /usr/bin/awk '/" & processToMonitor & "$/ {print }'"
        if processCPU is "" then
            --the process is gone. We're done
            return
        end if

        --convert the shell script response string to a number
        set processCPU to processCPU as number
        --compare to the threshold of quitting
        if processCPU is less than 2.0 then
            tell application processToMonitor to quit
        end if
        delay 1
    end repeat
end quitOnLowCPU

我在每次重复时添加了一个 delay,因为无休止地重复脚本本身通常会成为 CPU 猪。