2

I'm really new to programming, I was wondering if there was a way to run a while loop in the background of code already running in Python?

I was thinking of something like

While True: print("gibberish") print("pass")

with an output of something like:

'gibberish gibberish pass gibberish.....'

(It doesn't have to be in this order as long as I get a similar result)

Some_dude
  • 139
  • 1
  • 8

3 Answers3

2

You can use either multiprocessing or threading:

def background_code():
    while some_condition:
        print("gibberish")

...
thread = threading.Thread(target=background_code, args=(), kwargs={})
thread.start()
print("pass")
...

Both multiprocessing and threading have very similar APIs, and which one to use depends on your use case - the distinction between processes and threads is not one for this question. You're probably going to want threading for what you're currently working on, but there are different situations in which you'd prefer one or the other.

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
1

You can refer to the following code.

import threading

def func1():
    for i in range(10):
        print("gibberish")

def func2():
    print("pass")

t1 = threading.Thread(target=func1)
t2 = threading.Thread(target=func2)


if __name__ == '__main__':
    t1.start()
    t2.start()

What it does is, runs the methods func1 and func2 concurrently so that the provided methods run as background task for each other.

Rabin Lama Dong
  • 2,422
  • 1
  • 27
  • 33
0

Here is something similar using asyncio (requires python 3.7+):

import asyncio

async def loop():
    while True:
        print("gibberish")
        await asyncio.sleep(0.5)

async def main():
    future = asyncio.ensure_future(loop())
    for i in range(100):
        print("pass")
        await asyncio.sleep(1)
    future.cancel()
asyncio.get_event_loop().run_until_complete(main())    

This will print two gibberish for each pass. You can change the sleep timing to change the ratio.

Here, main and loop are coroutines, where only one is executed at a time. The await ... calls are points where execution is potentially yielded to other coroutines.

abc
  • 924
  • 8
  • 19