繁体   English   中英

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

[英]How can I run two different code in Python at the same time?

我想运行 winsound 并同时打印 output。 这是我的代码:

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

我该怎么做?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM