Python Forum
How to execute code WHILE a function runs
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to execute code WHILE a function runs
#3
You can do this with threading. My logic is 1) start animation in a different thread, 2) run function 1 3) stop animation. Read this page to start learning about threading in python
import threading
import time

event = threading.Event()

def animation():
    bar = [
    " [=     ]",
    " [ =    ]",
    " [  =   ]",
    " [   =  ]",
    " [    = ]",
    " [     =]",
    " [    = ]",
    " [   =  ]",
    " [  =   ]",
    " [ =    ]",
    ]
    
    i = 0
    while True:
        print(bar[i % len(bar)], end="\r")
        was_set = event.wait(timeout=0.2)
        if was_set:
            break
        i += 1

def function1():
    time.sleep(4)

event.clear()
anim = threading.Thread(target=animation)
anim.start()

function1()
event.set()
anim.join() # <-- wait for anim to terminate
print()
Reply


Messages In This Thread
RE: How to execute code WHILE a function runs - by Gribouillis - Jan-24-2020, 03:50 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How to do 100 runs simulation based on the current codes? dududada 6 1,001 Sep-03-2023, 01:43 PM
Last Post: deanhystad
  Another program runs bho68 7 1,211 Nov-08-2022, 08:16 PM
Last Post: bho68
  Can a program execute code in iPython shell and get result? deanhystad 3 1,760 Jun-17-2022, 03:45 AM
Last Post: Larz60+
  Importing a function from another file runs the old lines also dedesssse 6 2,577 Jul-06-2021, 07:04 PM
Last Post: deanhystad
  Putting code into a function breaks its functionality, though the code is identical! PCesarano 1 2,004 Apr-05-2021, 05:40 PM
Last Post: deanhystad
  Picking a function to execute palladium 1 1,622 Feb-09-2021, 04:47 PM
Last Post: deanhystad
  [split] SyntaxError when trying to execute code on Windows nehaya 2 2,014 Aug-04-2020, 11:18 AM
Last Post: nehaya
  How to create an Excel app that runs Python? felipe0216 3 2,285 May-31-2020, 01:19 AM
Last Post: ibutun
  SyntaxError when trying to execute code on Windows Fred0n 2 2,436 Apr-25-2020, 04:30 AM
Last Post: buran
  Python Program Runs in Pycharm but not in Terminal Vbhardwaj2383 2 3,315 Apr-06-2020, 04:41 PM
Last Post: Vbhardwaj2383

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020