gpt4 book ai didi

python-3.x - 来自多个文件的Python多线程

转载 作者:行者123 更新时间:2023-12-05 04:16:25 26 4
gpt4 key购买 nike

这是我想如何使用线程的示例演示。

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)

如何从多个文件制作这个线程工作演示?

例子:

# 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 """

第二个文件:

# background.py

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

最佳答案

for 循环之前的所有行放在 background.py 中。当它被导入时,它会启动线程运行。更改 run 方法以执行无限 while 循环。

您可能还想在启动线程时设置 daemon=True,这样它会在主程序退出时退出。

主.py

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

背景.py

import threading
import time

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

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

输出

background
middle
background
middle
background
background
background
middle
background
background
middle
background
background

关于python-3.x - 来自多个文件的Python多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27879879/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com