3

This is a sample demo of how I want to use threading.

import threading
import time

def run():
    print("started")
    time.sleep(5)
    print("ended")


thread = threading.Thread(target=run)
thread.start()

for i in range(4):
    print("middle")
    time.sleep(1)

How can I make this threading work demo even from multiple files?

Example:

# Main.py 
import background

""" Here I will have a main program and \
I want the command from the background file to constantly run. \
Not just once at the start of the program """

The second file:

# background.py

while True:
    print("This text should always be printing \
        even when my code in the main function is running")

1 Answer 1

3

Put all the lines before your for loop in background.py. When it is imported it will start the thread running. Change the run method to do your infinite while loop.

You may also want to set daemon=True when starting the thread so it will exit when the main program exits.

main.py

import time
import background
for i in range(4):
    print("middle")
    time.sleep(1)

background.py

import threading
import time

def run():
    while True:
        print("background")
        time.sleep(.5)

thread = threading.Thread(target=run,daemon=True)
thread.start()

Output

background
middle
background
middle
background
background
background
middle
background
background
middle
background
background
Sign up to request clarification or add additional context in comments.

Comments