使用 APPLESCRIPT 获取特定进程的 CPU 用法

Getting CPU usage of a specific process using APPLESCRIPT

我真的是 applescript 的新手,如果你能就我的问题提出建议,那肯定会有很大的帮助。

我目前正在尝试使用脚本编辑器创建一个脚本,该脚本可以检查 Google Chrome 当前的 CPU 使用率是否超过 50%。但是,我不确定测试的返回值是整数形式还是字符串形式。我在将“测试”与特定数字进行比较时遇到问题。你能帮我检查一下我做错了什么吗?谢谢你。这是我当前完整的 applescript,它会无限期运行,直到 Google Chrome CPU 使用率达到 50%(这里的主要问题是我不确定比较测试 <“50.0”):

getProcessPercentCPU("Google Chrome")

on getProcessPercentCPU(someProcess)
    set test to do shell script "/bin/ps -xco %cpu,command | /usr/bin/awk '/" & someProcess & "$/ {print }'"
    
    repeat while test < "50.0"
        set test to do shell script "/bin/ps -xco %cpu,command | /usr/bin/awk '/" & someProcess & "$/ {print }'"
    end repeat
    
    display dialog test
    
    
    
end getProcessPercentCPU

如果“测试”达到 50.0 或更高,此脚本应该会显示一个对话框。但是对话框返回值不准确或者不是50以上。请帮忙

在此先感谢您的帮助!

在此用例中,您不需要使用 可执行文件 完全限定路径名 作为 psawkPATH 内传递给 do shell script 命令 ,即:/usr/bin:/bin:/usr/sbin:/sbin

此外,您不需要执行两次do shell script 命令。只需在 repeat loop 之前设置 testvalue,然后在结果上使用 as integer do shell script 命令的 例如:

getProcessPercentCPU("Google Chrome")

on getProcessPercentCPU(someProcess)
    
    set test to 0
    
    repeat while test < 50
        set test to ¬
            (do shell script "ps -xco %cpu,command | awk '/" & someProcess & "$/ {print }'") ¬
                as integer
    end repeat
    
    display dialog test
    
end getProcessPercentCPU

也就是说,像这样使用 loop 会占用大量资源,因此您可以考虑添加 delay commandloop 内部,因此 do shell script command 不会连续不断地触发一次迭代。此外,考虑使用一些方法在给定的时间段后逃离循环

添加了delay超时

getProcessPercentCPU("Google Chrome")

on getProcessPercentCPU(someProcess)
    
    set i to 0
    set test to 0
    
    repeat while test < 50
        set test to ¬
            (do shell script "ps -xco %cpu,command | awk '/" & someProcess & "$/ {print }'") ¬
                as integer
        delay 2
        set i to i + 1
        if i ≥ 10 then exit repeat      
    end repeat
    
    display dialog test
    
end getProcessPercentCPU