我的AppleScript中有ASObjC Runner代码,一旦do shell script
运行,就会显示进度窗口。如何使进度窗口上的按钮终止shell脚本?
以下是我的代码示例:
tell application "ASObjC Runner"
reset progress
set properties of progress window to {button title:"Abort", button visible:true, indeterminate:true}
activate
show progress
end tell
set shellOut to do shell script "blahblahblah"
display dialog shellOut
tell application "ASObjC Runner" to hide progress
tell application "ASObjC Runner" to quit
答案 0 :(得分:2)
答案有几个部分:
异步do shell script
:通常,do shell script
仅在shell命令完成后返回,这意味着您无法对shell内的进程执行操作。但是,您可以通过backgrounding执行的Apple’s Technical Note TN2065命令获得do shell script
命令,即
do shell script "some_command &> /target/output &"
- 在启动shell命令后立即返回。由于它不会返回命令的输出,因此您必须自己捕获它,例如在文件中(或者如果您不需要,则重定向到/dev/null
)。如果将echo $!
附加到命令,do shell script
将返回后台进程的PID。基本上,做
set thePID to do shell script "some_command &> /target/output & echo $!"
见{{3}}。然后停止该过程只需要做do shell script "kill " & thePID
。
挂钩 ASObjC Runner 的进度对话框只是轮询其button was pressed
属性并打破true
:
repeat until (button was pressed of progress window)
delay 0.5
end repeat
if (button was pressed of progress window) then do shell script "kill " & thePID
决定何时完成shell脚本以关闭进度对话框这是一个有趣的部分,因为shell命令是异步操作的。您最好的选择是使用您检索到的PID来ps
,以检查该过程是否仍在运行,即
if (do shell script "ps -o comm= -p " & thePID & "; exit 0") is ""
当进程不再运行时,将返回true
。
这将为您留下以下代码:
tell application "ASObjC Runner"
reset progress
set properties of progress window to {button title:"Abort", button visible:true, indeterminate:true}
activate
show progress
try -- so we can cancel the dialog display on error
set thePID to do shell script "blahblahblah &> /file/descriptor & echo $!"
repeat until (button was pressed of progress window)
tell me to if (do shell script "ps -o comm= -p " & thePID & "; exit 0") is "" then exit repeat
delay 0.5 -- higher values will make dismissing the dialog less responsive
end repeat
if (button was pressed of progress window) then tell me to do shell script "kill " & thePID
end try
hide progress
quit
end tell
如果您需要捕获后台shell命令的输出,则必须将其重定向到文件并在完成后读出该文件的内容,如上所述。