简体   繁体   中英

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

Im currently trying to make a playlist function to run in the background of my code. I am using threading and pygame, and the playlist is an array list. I keep getting this error:

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

this is the related snippet of code:

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 repository: https://github.com/M1st3rMinecraft/python-virtual-assistant

Try changing Thread(target=playPlaylist, args=(playlist)).start() to Thread(target=playPlaylist, args=(playlist, )).start() it helped in my case. And also check all of the elements in your code in which you are calling functions if they are not strings. If that didn't work share your file with the mixer class so I can help you further.

The args parameter is supposed to be an iterable (such as a tuple or list) where each element becomes an argument to the function playPlayList . When you specify args=(playlist) , the parentheses surrounding playlist does not denote a tuple of one element. For that you would need to specify args=(playlist,) . Therefore, the playlist itself is being interpreted as the iterable and each element of it will be considered a separate argument to playPlayList . There must be only currently one element in playlist for if there were, for example, 3, you would get an error message such as:

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

So you need to specify: args=(playlist,) . That's problem number one.

Since you are not being passed playlist any more but rather the first and only element of that list as the argument, that is probably leading to the second error. But I would think you would get the exception at:

for music in playlist:

But perhaps the first element of playlist is itself iterable. Try fixing the first problem, though, and see what happens.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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