Last active
March 3, 2017 02:36
-
-
Save teward/440ef1dc7c91b8d593f3cbed3eef991a to your computer and use it in GitHub Desktop.
Play a random MP3 file in a specified media player
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import getpass | |
import subprocess as sp | |
import os | |
import glob | |
import random | |
import argparse | |
if __name__ == "__main__": | |
# Parse arguments to the script | |
argparser = argparse.ArgumentParser(description="Open a random MP3 in the player of choice, or the default player", | |
add_help=True) | |
argparser.add_argument('--dir', '--directory', '--music-dir', dest='dirpath', type=str, | |
default=str('/home/' + getpass.getuser() + '/Music'), required=False, | |
help="The path to the directory where your music is stored. If the path has spaces, wrap the " | |
"entire path in single-quotes ('/home/ubuntu/My Music/' for example). If not specified, " | |
"the current user's Music directory in their /home/ folder is used.") | |
argparser.add_argument('player', type=str, help="The executable name of the media player " | |
"to open the MP3 with. If none specified, " | |
"uses the system default player.") | |
# Using the above 'argparser' items, get the arguments for what we're going to be using. | |
args = argparser.parse_args() | |
# Gp to the directory your music is in. | |
os.chdir(args.dirpath) | |
mp3s = glob.glob('*.mp3') | |
# Modify the directory path to make sure we have the trailing slash | |
dirpath = args.dirpath | |
if dirpath[-1] not in '/\\': | |
dirpath += '/' | |
# Actually open the MP3 file, and /dev/null to suppress output messages from the process. | |
DEV_NULL = open(os.devnull, 'w') | |
execpath = [args.player, '%s%s' % (dirpath, str(random.choice(mp3s)))] | |
sp.Popen(execpath, stdout=DEV_NULL, stderr=DEV_NULL) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment