Skip to content

Commit 5cfae11

Browse files
committed
fix traceback issue with quit()
make script more readable using functions add function descriptions add more user prints and guidance perform manual integration tests
1 parent 6a883ea commit 5cfae11

1 file changed

Lines changed: 102 additions & 80 deletions

File tree

AutoStructureFilesForDFplayer.py

Lines changed: 102 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -1,137 +1,159 @@
1-
import os, os.path
1+
import os
2+
from sys import exit
3+
import os.path
24
import shutil
35

4-
#this function pads leading zeros to a number, returning a string.
5-
def playerFSnumbers(folderIndex, maxCnt):
6-
if folderIndex > maxCnt:
7-
print("Error: player cannot process more than 100 folders")
8-
input("Press Enter to quit...")
9-
quit()
10-
return str(folderIndex).zfill(len(str(maxCnt)))
6+
#Author: L. Preusser "Schallbert"
117

12-
#folder names
8+
# this function pads leading zeros to a number, returning a string.
9+
def playerFSnumbers(indx, maxCnt):
10+
"""This function returns a DFplayerMini-compatible way of numbering
11+
files which is 001, 002, ... 255"""
12+
if indx > maxCnt:
13+
quitWithMessage("Error: player cannot process more than 100 folders")
14+
return str(indx).zfill(len(str(maxCnt)))
15+
16+
def replaceSpecialCharactersInPlaylist(lineOfPlaylist):
17+
"""Make sure .m3u file's special characters are converted
18+
Replace most commont HTML exclamations"""
19+
lineOfPlaylist = lineOfPlaylist.replace("%20", " ")
20+
lineOfPlaylist = lineOfPlaylist.replace("%21", "!")
21+
lineOfPlaylist = lineOfPlaylist.replace("%22", '"')
22+
lineOfPlaylist = lineOfPlaylist.replace("%23", "#")
23+
lineOfPlaylist = lineOfPlaylist.replace("%24", "$")
24+
lineOfPlaylist = lineOfPlaylist.replace("%25", "%")
25+
lineOfPlaylist = lineOfPlaylist.replace("%26", "&")
26+
lineOfPlaylist = lineOfPlaylist.replace("%27", "'")
27+
lineOfPlaylist = lineOfPlaylist.replace("%28", "(")
28+
lineOfPlaylist = lineOfPlaylist.replace("%29", ")")
29+
lineOfPlaylist = lineOfPlaylist.replace("%2A", "*")
30+
lineOfPlaylist = lineOfPlaylist.replace("%2B", "+")
31+
lineOfPlaylist = lineOfPlaylist.replace("%2C", ",")
32+
lineOfPlaylist = lineOfPlaylist.replace("%2D", "-")
33+
lineOfPlaylist = lineOfPlaylist.replace("%2E", ".")
34+
lineOfPlaylist = lineOfPlaylist.replace("%2F", "/")
35+
lineOfPlaylist = lineOfPlaylist.replace("%3A", ":")
36+
lineOfPlaylist = lineOfPlaylist.replace("%3B", ";")
37+
lineOfPlaylist = lineOfPlaylist.replace("%3C", "<")
38+
lineOfPlaylist = lineOfPlaylist.replace("%3D", "=")
39+
lineOfPlaylist = lineOfPlaylist.replace("%3E", ">")
40+
lineOfPlaylist = lineOfPlaylist.replace("%3F", "?")
41+
return lineOfPlaylist
42+
43+
def quitWithMessage(messageString):
44+
"""Quits script gracefully with message"""
45+
print(messageString)
46+
input("Press Enter to quit...")
47+
sys.exit()
48+
49+
print("\
50+
Starting Conversion script for structuring files for DFplayerMini.\n\
51+
This script analyzes .m3u playlists and restructures their contents to a format\n\
52+
readable by the DFmini mp3 module.\n\n")
53+
54+
# folder names
1355
plFldrName = "PlayListsM3U"
1456
crdFldrName = "SDcardFolders"
15-
#player's maximum accepted file cnt
57+
# player's maximum accepted file cnt
1658
maxFldrCnt = 99
1759
maxFileCnt = 255
60+
listOfPlaylists = None
1861

19-
#get current working directory
62+
# get current working directory
2063
myPath = os.getcwd()
21-
#create directories for playlists and target folders
64+
# create directories for playlists and target folders
2265
plPath = os.path.join(os.sep, myPath, plFldrName)
2366
crdPath = os.path.join(os.sep, myPath, crdFldrName)
24-
listOfPlaylists = None
2567
tgtFldrPath = -1
2668
tgtFileName = -1
2769

28-
#Check for playlist path
70+
print("Hooked to current working directory: %s" % myPath)
71+
72+
# Check for playlist path
2973
if not os.path.exists(plFldrName):
30-
print("Did not find folder containing m3u playlists.\nTrying to create folder 'PlayListsM3U' for you.\nPlease move your playlists to this place before restarting the script.")
74+
print("\
75+
Did not find folder containing m3u playlists.\n\
76+
Trying to create folder 'PlayListsM3U' for you.")
3177
try:
3278
os.makedirs(plFldrName)
3379
except:
34-
print("Couldn't create folder. Is directory read-only?")
35-
input("Press Enter to quit...")
36-
quit()
80+
quitWithMessage("Couldn't create folder. Is directory read-only?")
81+
quitWithMessage("\
82+
Playlist folder successfully created: %s\n\
83+
Please move your playlists to this place before restarting the script." % plFldrName)
3784
else:
38-
#if Playlist folder exists, print playlists to be evaluated.
85+
# if Playlist folder exists, print playlists to be evaluated.
3986
listOfPlaylists = os.listdir(plFldrName)
4087
listOfPlaylists.sort()
4188
print("Folder containing playlists found. Will try creating DFplayer folders and files for:")
4289
print(listOfPlaylists)
43-
#input("Press Enter to continue...")
44-
45-
#Check for album(folder) path
90+
# input("Press Enter to continue...")
91+
92+
# Check for album(folder) path
4693
if not os.path.exists(crdFldrName):
47-
print("Did not find folder containing SD card MP3 folders.\nTrying to create folder 'SDcardFolders' for you.\nYou will find the files to transfer to Tonuino in this folder.")
94+
print("\
95+
Did not find folder containing SD card MP3 folders.\n\
96+
Trying to create folder 'SDcardFolders' for you.\n \
97+
You will find the files to transfer to your DFplayerMini's SD card in this folder.")
4898
try:
4999
os.makedirs(crdFldrName)
50100
except:
51-
print("Couldn't create folder. Is directory read-only?")
52-
input("Press Enter to quit...")
53-
quit()
101+
quitWithMessage("Couldn't create folder. Is directory read-only?")
54102
else:
55-
#if Playlist folder exists, print playlists to be evaluated.
103+
# if Playlist folder exists, print playlists to be evaluated.
56104
listOfCardFolders = os.listdir(crdFldrName)
57105
print("Folder containing SDcard MP3 folders found. Will modify folder structure based on playlist input.")
58-
print(listOfCardFolders)
106+
print("Existing folders: " + str(listOfCardFolders))
59107

60-
#create folders with correct naming to contain mp3 files
108+
# create folders with correct naming to contain mp3 files
61109
folderIndex = 0
62110
fName = ""
63111
lineLower = ''
64-
if listOfPlaylists is not None:
65-
print(listOfPlaylists)
66-
#Go through all .m3u files in .m3u folder
112+
if listOfPlaylists:
113+
print("Playlists found: " + str(listOfPlaylists))
114+
# Go through all .m3u files in .m3u folder
67115
for item in listOfPlaylists:
68116
os.chdir(crdPath)
69117
folderIndex += 1
70-
#get folderIndexes right according to player's needs
118+
# get folderIndexes right according to player's needs
71119
fName = playerFSnumbers(folderIndex, maxFldrCnt)
72120
if not os.path.exists(fName):
73121
try:
74122
os.makedirs(fName)
75123
except:
76-
print("Couldn't create folder. Is directory read-only?")
77-
input("Press Enter to quit...")
78-
quit()
124+
quitWithMessage("Couldn't create folder. Is directory read-only?")
79125
else:
80-
#folder already exists. Auto-Overwrite.
81-
print("Folder '%s' exists. Will auto-overwrite contents." % (fName,))
82-
#go through all playlists in folder
126+
# folder already exists. Auto-Overwrite.
127+
print("Folder '%s' exists. Will auto-overwrite contents." % fName)
128+
# go through all playlists in folder
83129
tgtFldrPath = os.path.join(os.sep, crdPath, fName)
84130
os.chdir(plPath)
85-
#playlist open and show
86-
if item.find(str(fName), 0, 4) == -1: #tries to find out if playlist has been used already, returns -1 if no duplicates
131+
# playlist open and show
132+
if item.find(str(fName), 0,
133+
4) == -1: # tries to find out if playlist has been used already, returns -1 if no duplicates
87134
try:
88135
os.rename(str(item), fName + " " + str(item))
89136
item = fName + " " + str(item)
90137
except:
91-
print("Couldn't rename playlist " + str(item) + ". Aborting.")
92-
input("Press Enter to quit...")
93-
quit()
138+
quitWithMessage("Couldn't rename playlist " + str(item) + ". Aborting.")
94139
playlistFile = open(item, "r")
95140
fileIndex = 0
96141
for line in playlistFile.readlines():
97-
lineLower = line.lower() #convert to lower case to also find .MP3
98-
if lineLower.find("file:") > -1: #only list lines that describe MP3 file path
99-
fileIndex +=1
142+
lineLower = line.lower() # convert to lower case to also find .MP3
143+
if lineLower.find(".mp3") > -1: # only list lines that describe MP3 file path
144+
fileIndex += 1
100145
fName = playerFSnumbers(fileIndex, maxFileCnt)
101146
tgtFileName = os.sep + fName + ".mp3"
102-
line = line.strip() #strip removes New Line markers \n
103-
if line.find("file:///") > - 1: #strip line of file marker within m3u
147+
line = line.strip() # strip removes New Line markers \n
148+
if line.find("file:///") > - 1: # strip line of file marker within m3u
104149
line = line.split("file:///")[-1]
105-
#Also replace most commont HTML exclamations
106-
line = line.replace("%20", " ")
107-
line = line.replace("%21", "!")
108-
line = line.replace("%22", '"')
109-
line = line.replace("%23", "#")
110-
line = line.replace("%24", "$")
111-
line = line.replace("%25", "%")
112-
line = line.replace("%26", "&")
113-
line = line.replace("%27", "'")
114-
line = line.replace("%28", "(")
115-
line = line.replace("%29", ")")
116-
line = line.replace("%2A", "*")
117-
line = line.replace("%2B", "+")
118-
line = line.replace("%2C", ",")
119-
line = line.replace("%2D", "-")
120-
line = line.replace("%2E", ".")
121-
line = line.replace("%2F", "/")
122-
line = line.replace("%3A", ":")
123-
line = line.replace("%3B", ";")
124-
line = line.replace("%3C", "<")
125-
line = line.replace("%3D", "=")
126-
line = line.replace("%3E", ">")
127-
line = line.replace("%3F", "?")
128-
129-
tgtFileName = fName + ".mp3" #new target file name
150+
line = replaceSpecialCharactersInPlaylist(line)
151+
tgtFileName = fName + ".mp3" # new target file name
130152
try:
131-
print("Working...\n")
132-
shutil.copy2(line, os.path.join(os.sep, tgtFldrPath, tgtFileName)) #copies & renames file from playlist to target folder
153+
shutil.copy2(line, os.path.join(os.sep, tgtFldrPath,
154+
tgtFileName)) # copies & renames file from playlist to tgt folder
133155
except:
134-
print("Couldn't copy file\n" + str(line) + " to:\n" + str(tgtFldrPath) + "\nAborting.")
135-
quit()
136-
print("Successfully copied %s files!" % (fileIndex,))
137-
input("\n\nPress Return to quit")
156+
quitWithMessage("Couldn't copy file\n" + str(line) + " to:\n" + str(tgtFldrPath) + "\nAborting.")
157+
quitWithMessage("Successfully copied %s files!" % fileIndex)
158+
else:
159+
quitWithMessage("No playlists found in folder. Aborting.")

0 commit comments

Comments
 (0)