applescript - 使用 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 或更大。请帮忙。
在此先感谢您的帮助!
解决方案
在此用例中,您不需要使用可执行文件的完全限定路径名,因为两者都在传递给命令的范围内,即:ps
awk
PATH
do shell script
/usr/bin:/bin:/usr/sbin:/sbin
此外,您不需要执行该do shell script
命令两次。只需在循环之前设置 的值,然后在命令的结果上使用,例如:test
repeat
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 $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
推荐阅读
- progressive-web-apps - PWA 离线检查 - 类型错误:[start_url] 的网络请求引发错误:无法获取
- sql - TSQL 查询的问题仅根据需要返回具有值而不是 0 的月份
- python - Pygame 砖块在碰撞时会消失,但会在几秒钟内重新出现
- c - 我需要使用哪些标头变量来提取 tar 文件
- javascript - 如何使用 Heroku 上的库部署 monorepo
- python - Discord.py 将角色添加到成员
- python - 在不改变颜色的情况下将 CMYK 转换为 RGB
- c# - 如何使韵律持续时间适用于所有语音性别?
- python - 下载错误:错误:警告:无法在 heroku 中使用 ffprobe 获取文件音频编解码器
- python - pvlib 未校正 calcparams_desoto 中的串联电阻和校正分流电阻,与参考不一致