Bash 未终止 python 脚本

Bash not terminating python script

我正在尝试 运行 一个简单的动画 python 脚本,同时 bash 执行一些文件。但是,一旦 bash 脚本完成,动画脚本就不会正确终止。

python 脚本完美运行。如果我在 Bash 中使用 运行 原生的不同动画,bash 脚本就可以工作。但是如果我得到 bash 到 运行 的 python 脚本,它会永远 运行 吗?

Bash 脚本:

#!/usr/bin/env bash

# Don't leave animation running if files executed.
unset anim_pid
trap 'kill $anim_pid 2>/dev/null' EXT INT
# Get animation script
animation() {
      python "/home/solebay/Project/loading_animation.py"
}

animation & anim_pid=$!

# Scripts to execute
python "/home/solebay/Project/script_a" & pid1=$!
python "/home/solebay/Project/script_b" & pid2=$!

# wait for tasks to finish
wait $pid1 $pid2
kill $anim_pid 2>/dev/null

printf '\n *** End of script ***\n'

Python loading_animation.py:

#!/usr/bin/env python

import itertools
import threading
import time
import sys

# Please wait message
msg = "\nPlease wait a moment..."
for idx, i in enumerate(msg):
    if idx <= 19:
        sys.stdout.write(i)
        sys.stdout.flush()
        time.sleep(0.02)
    else:
       sys.stdout.write(i)
       sys.stdout.flush()
       time.sleep(0.6)
# Spinning part
for c in itertools.cycle(['|', '/', '-', '\']):
    sys.stdout.write('\rPlease wait a moment... ' + c)
    sys.stdout.flush()
    time.sleep(0.1)

最终它不起作用,动画打印错误,然后永远旋转。这是因为我正在尝试使用多线程然后让线程保持打开状态吗?或者,永无休止的加载脚本是不是一个糟糕的主意?

问题是您 putting the function in the background 然后终止该函数,而不是 运行 里面的命令。

相反,您可以调用脚本而不用函数包装它:

python "/home/solebay/Project/loading_animation.py" &
anim_pid=$!