我正在嘗試靜默運行腳本和加載影片。我希望在執行初始腳本后終止加載影片,以便可以執行最終腳本。
run A.py |
| --> message ∞ load animation | --> run C.py (uses A & B output)
run B.py |
我已經完成了 80%,但我使用的方法會等待無限加載影片完成,然后再繼續。顯然,它永遠不會結束,也永遠不會繼續(我有一個解決方法,但我不太喜歡它,我已經投入時間試圖讓這種當前方法發揮作用)。
# Run these silently
python "/home/solebay/Project/script_a.py" &
python "/home/solebay/Project/script_b.py" &
pid=$!
# If this script is killed, stop the loading animation.
trap "kill $pid 2> /dev/null" EXIT
# While is running...
message=false
while kill -0 $pid 2> /dev/null; do
if [ "$message" = false ]; then
python "/home/solebay/Projects/loading_message.py" # print loading message
message=true
fi
python "/home/solebay/Project/loading_animation.py" # Print looping animation
done
trap - EXIT
# Run the main script (dependent on script_a.py and script_b.py)
python "/home/solebay/Project/script_c.py"
我可以修改這種方法以使其有效還是不合適?我所嘗試的一切最終都只是將它帶回到一個不起作用的狀態。
實施 Léa Gris 的解決方案:
unset anim_pid
trap 'kill $anim_pid' EXT INT
python "/home/solebay/Project/loading_animation.py" & anim_pid=$!
python /home/solebay/Project/script_a.py & pid1=$!
python /home/solebay/Project/script_b.py & pid2=$!
# wait -n either task to finish
wait $pid1 $pid2
kill $anim_pid 2>/dev/null
printf '\n *** End of script ***\n'
uj5u.com熱心網友回復:
wait -n pid pid將等待任一 pid 完成wait pid pid將等待兩個 pid 完成
#!/usr/bin/env bash
# Do not leave animation running in case script ends
unset anim_pid
trap 'kill $anim_pid 2>/dev/null' EXT INT
animation() {
# loop until killed
while :; do
for frame in '|' '/' '-' \\; do
printf '\r%s' "$frame"
sleep .25
done
done
}
task() {
printf 'Hello I am task %d\n' "$1"
LC_NUMERIC=C printf 'Task %d sleeping for %f seconds\n' "$1" "$2"
sleep "$2"
printf 'Task %d finished\n' "$1"
}
animation & anim_pid=$!
task 1 2.2 & pid1=$!
task 2 1.5 & pid2=$!
# wait both tasks to finish
wait $pid1 $pid2
kill $anim_pid 2>/dev/null
printf '\n *** End of script ***\n'
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/422230.html
標籤:
上一篇:bash手動回圈遍歷目錄中的檔案
下一篇:jq不會將值注入json檔案
