0

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?

1 Answer 1

2

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=$!
Sign up to request clarification or add additional context in comments.

2 Comments

May I ask, why the variable anim_pid is not evaluated in the trap? How else can we pass variables to the trap? I guess putting them into the environment wouldn't help either.
@user1934428 You are right, I was mistaken, it will be evaluated when invoked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.