gpt4 book ai didi

Python,如何在不停止其余代码执行的情况下执行一行代码?

转载 作者:行者123 更新时间:2023-12-05 02:28:38 33 4
gpt4 key购买 nike

首先,我是初学者。我想要完成的是在脚本执行时播放音乐。它现在所做的是播放音乐,等到音乐结束,然后执行其余代码。那不是我想要的。这是我的代码:

import os
import subprocess
import multiprocessing
import threading
from playsound import playsound
CurrentPath = os.path.dirname(os.path.normpath(__file__))
os.chdir(CurrentPath)

def music():
Music = "Music.mp4"
#subprocess.run(["ffplay", "-nodisp", "-autoexit", "-hide_banner", Music])
playsound("Music.mp4")

def other_things():
print("Hello World")

#musicp = multiprocessing.Process(target=music())
#restp = multiprocessing.Process(target=other_things())
musicp = threading.Thread(target=music())
restp = threading.Thread(target=other_things())

restp.start()
musicp.start()

就像你看到的那样,我什至尝试过多线程,但它仍然要等到音乐结束才转到其余代码。

最佳答案

不要调用 Thread 函数的目标参数中的函数 - 删除括号以引用函数,而不是其返回值

musicp = threading.Thread(target=music) # instead of music()
restp = threading.Thread(target=other_things) # instead of other_things()

关于Python,如何在不停止其余代码执行的情况下执行一行代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72584542/

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