【问题标题】:Getting CPU usage of a specific process using APPLESCRIPT使用 APPLESCRIPT 获取特定进程的 CPU 使用率
【发布时间】:2020-08-26 00:20:59
【问题描述】:

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

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

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


    【解决方案1】:

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

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

    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
    

    也就是说,使用像这样的 loop 会占用大量资源,因此您可以考虑在 loop 内添加 delay command > 所以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 $1}'") ¬
                    as integer
            delay 2
            set i to i + 1
            if i ≥ 10 then exit repeat      
        end repeat
        
        display dialog test
        
    end getProcessPercentCPU
    

    【讨论】:

    • 感谢您的回复!我会试试你的建议。我对脚本世界真的很陌生,所以我试图一点一点地完全理解一切。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-10-16
    • 2011-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多