Home > Software engineering >  Bash not terminating python script
Bash not terminating python script

Time:01-26

I'm trying to run a simple animated python script while bash executes some files. However the animation script isn't properly terminating once the bash script is done.

The python script works perfectly. If I use a different animation that runs natively in Bash, the bash script works. But if I get bash to run the python script, it runs forever?

Bash Script:

#!/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)

Ultimately it doesn't work and the animation mis-prints and then spins forever. Is this because I'm trying to use multithreading and then leaving threads open? Alternatively, are never-ending loading scripts a terrible idea?

CodePudding user response:

The problem is that you are putting the function in the background and then killing that function, but not the command that's running inside.

Instead you can invoke the script without wrapping it by a function:

python "/home/solebay/Project/loading_animation.py" &
anim_pid=$!
  •  Tags:  
  • Related