簡體   English   中英

Python - 線程 - 如何創建播放列表函數以使用線程在后台運行?

[英]Python - threading - how do I create a playlist function to run in the background with threading?

我目前正在嘗試使播放列表功能在我的代碼后台運行。 我正在使用線程和 pygame,播放列表是一個數組列表。 我不斷收到此錯誤:

Exception in thread Thread-4:
Traceback (most recent call last):
  File "C:\Users\harry\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in 
_bootstrap_inner

    self.run()
  File "C:\Users\harry\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
TypeError: 'str' object is not callable

這是相關的代碼片段:

from threading import Thread
from time import sleep

def playPlaylist(playlist):
    mixer.init()
    for music in playlist:
        mixer.music.load(music)
        mixer.music.play()
        while mixer.music.get_busy():
            sleep(1)

Thread(target=playPlaylist, args=(playlist)).start()

Github 存儲庫: https : //github.com/M1st3rMinecraft/python-virtual-assistant

嘗試將Thread(target=playPlaylist, args=(playlist)).start()更改為Thread(target=playPlaylist, args=(playlist, )).start()它對我有幫助。 如果它們不是字符串,還要檢查代碼中調用函數的所有元素。 如果這不起作用,請與混音器類共享您的文件,以便我可以進一步幫助您。

args參數應該是一個iterable (例如元組或列表),其中每個元素都成為函數playPlayList的參數。 當指定args=(playlist) ,圍繞括號playlist並不表示一個元素的元組。 為此,您需要指定args=(playlist,) 因此, playlist本身被解釋為可迭代的,並且它的每個元素都將被視為playPlayList的單獨參數。 playlist當前必須只有一個元素,例如,如果有 3 個元素,您將收到一條錯誤消息,例如:

TypeError: playPlaylist() takes 1 positional argument but 3 were given

所以你需要指定: args=(playlist,) 這是第一個問題。

由於您不再被傳遞playlist ,而是該playlist的第一個也是唯一一個元素作為參數,這可能會導致第二個錯誤。 但我認為您會在以下位置獲得例外:

for music in playlist:

但也許playlist的第一個元素本身是可迭代的。 不過,請嘗試解決第一個問題,然后看看會發生什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM