Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python multithreading from multiple files

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 Answers

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
like image 164
Mark Tolonen Avatar answered Jan 27 '26 00:01

Mark Tolonen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!