Home > Software engineering >  Running one bit of code while another is computing
Running one bit of code while another is computing

Time:07-30

I have this line of code:

c_drive_dirs = [curdir for curdir, _, _ in os.walk(os.getcwd())]

while it's running I would like it to run a separate piece of code, for example:

print("/", end="\r")
print("-", end="\r")
print("\\", end="\r")
print("|", end="\r")

And I want this code to continue running while the 1st line of code is running, then run a different piece of code, for example:

print("")

In order to clear the screen of the loading effect

How would this be done?

(is there a python equivalent of C 's do-while loop?)

CodePudding user response:

You could use asyncio to create a background task and use a boolean to control it:

import asyncio
import os

started = False
async def print_head(): 
    while True: 
        # print("")
        if not started: 
            break

        print("/", end="\r")
        print("-", end="\r")
        print("\\", end="\r")
        print("|", end="\r")

async def main():
    global started

    started = True
    await asyncio.create_task(print_head())
    c_drive_dirs = [curdir for curdir, _, _ in os.walk(os.getcwd())]
    started = False

    print(c_drive_dirs)

asyncio.run(main())

CodePudding user response:

Both of these functions are blocking, threading/using asynchronous code will not allow both of them to run at the same time.

you can either use multiprocessing to run the print loop:

import os
import time
from multiprocessing import Process, Event
from itertools import cycle

def print_loading(event):
    c = cycle(["/", "-", "\\", "|"])
    while True:
        if event.is_set():
            break
        print(next(c), end="\r", flush=True)
        time.sleep(0.1)


def load_files():
    event = Event()
    p = Process(target=print_loading, args=(event,))
    p.daemon = True
    p.start()
    c_drive_dirs = [curdir for curdir, _, _ in os.walk(os.getcwd())]
    time.sleep(10)  # put this here for testing, remove in your code
    event.set()
    p.join()
    print(c_drive_dirs)


if __name__ == "__main__":
    load_files()

or just a simple function:

import os

def load_files():
    c = cycle(["/", "-", "\\", "|"])

    c_drive_dirs = []
    for curdir, _, _ in os.walk(os.getcwd()):
        c_drive_dirs.append(curdir)
        print(next(c), end="\r")
    print("\n")
    return c_drive_dirs

if __name__ == "__main__":
    res = load_files()
    print(res)

Or use a library:

from progress.spinner import Spinner

spinner = Spinner('Loading ')

c_drive_dirs = []
for curdir, _, _ in os.walk(os.getcwd()):
    c_drive_dirs.append(curdir)
    spinner.next()
  • Related