Python Forum
Running files using random - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Running files using random (/thread-20990.html)



Running files using random - ebolisa - Sep-09-2019

Hi,

The following code plays a mp3 file from a folder randomly. After few days running, it stops but I just cannot find the problem/cause. What king of checks should I add into the code to trap the culprit line?

TIA

#!/usr/bin/python3

from __future__ import print_function
import random, os
import pygame
import logging

#music files path
path = "/media/usb/"

#get music files
songs = os.listdir(path)

#filter mp3 files
songs = [fi for fi in songs if fi.endswith(".mp3")]

pygame.init()
pygame.mixer.init()
#print(pygame.mixer.get_init())

def play_songs():
    try:
        #pygame.mixer.music.set_volume(0.50)
        filename = random.choice(songs)
        #print('playing now {}'.format(filename))
        pygame.mixer.music.load(path + filename)
        pygame.mixer.music.play()
        while pygame.mixer.music.get_busy():
            pygame.time.Clock().tick(10)
    except ValueError:
	    logging.exception("msg from music.py: " +format(ValueError))
        print('Excemption: {}', format(ValueError))

if __name__ == '__main__':
    while True:
        play_songs()



RE: Running files using random - wavic - Sep-09-2019

Just define a main function:
import sys

def main():
    while True:
        play_songs()

if __name__ == '__main__':
    sys.exit(main())
That way you get the return code of the script.


RE: Running files using random - ebolisa - Sep-10-2019

So, if I understand the code right, it loops regardeless of the error (if any)?
Thank you.


RE: Running files using random - wavic - Sep-10-2019

This is an addition to your code. A wrapper function for the last if block. When it happens to stop again you should see the exit code of the program and you can make assumptions about the reason.


RE: Running files using random - ebolisa - Sep-10-2019

I see, unfortunatelly, the board is not connected to a monitor. I can only see the errors in the syslog.


RE: Running files using random - wavic - Sep-12-2019

You can just redirect the output to a file and then you can read it.

my_scipt.py > /path/exit_status.txt