如何在Python中同时运行两个不同的代码?

2024-06-25 07:18:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我想运行winsound并同时打印输出。这是我的密码:

winsound.PlaySound(filename, winsound.SND_FILENAME)
print('a')

我该怎么做


Tags: 密码filenameprint打印输出sndwinsoundplaysound
2条回答

您需要使用this答案中所示的线程

import winsound
from threading import Thread

def play_sound():
    winsound.PlaySound(filename, winsound.FILENAME)

thread = Thread(target=play_sound)
thread.start()
print ('a')

pip安装多处理

import multiprocessing
import time

def random_stuff_to_do():
    time.sleep(1)
    print("Slept 1 second")

task1 = multiprocessing.Process(target = random_stuff_to_do)
task2 = multiprocessing.Process(target = random_stuff_to_do)

task1.start()
task2.start()

task1.join() #This part is usefull only if you want to wait for your tasks to end 
task2.join() #before the program to continue.

print("Task 1 and 2 done at the same time")

相关问题 更多 >