首页 > 解决方案 > 使用 APPLESCRIPT 获取特定进程的 CPU 使用率

问题描述

我对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 $1}'"
    
    repeat while test < "50.0"
        set test to do shell script "/bin/ps -xco %cpu,command | /usr/bin/awk '/" & someProcess & "$/ {print $1}'"
    end repeat
    
    display dialog test
    
    
    
end getProcessPercentCPU

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

在此先感谢您的帮助!

标签: applescript

解决方案


在此用例中,您不需要使用可执行文件的完全限定路径名,因为两者都在传递给命令的范围内,即:psawkPATHdo shell script /usr/bin:/bin:/usr/sbin:/sbin

此外,您不需要执行该do shell script 命令两次。只需在循环之前设置 的,然后在命令的结果上使用,例如:testrepeat as integerdo 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 $1}'") ¬
                as integer
    end repeat
    
    display dialog test
    
end getProcessPercentCPU

也就是说,使用这样的循环可能会占用大量资源,因此您可以考虑在循环内添加一个delay 命令,这样该命令就不会在一个迭代之后直接触发。此外,考虑在给定时间段后使用某种方法来逃避循环。do shell script

添加了一个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 $1}'") ¬
                as integer
        delay 2
        set i to i + 1
        if i ≥ 10 then exit repeat      
    end repeat
    
    display dialog test
    
end getProcessPercentCPU

推荐阅读