Python,如何执行一行代码而不会停止其他代码的执行? 如何在Python中执行一行代码,同时不影响其他代码的执行?

3

首先,我是一个初学者。我想要实现的是在脚本执行过程中播放音乐。目前的情况是它会播放音乐,等待音乐播放完毕后再执行剩余的代码。这不是我想要的。以下是我的代码:

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

你可以看到,我甚至尝试了多线程,但它仍然会等待音乐结束才继续执行代码的其他部分。

1个回答

3

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接