首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >随机MP3选择器和播放器

随机MP3选择器和播放器
EN

Code Review用户
提问于 2017-03-03 02:44:11
回答 1查看 1.2K关注 0票数 5

所以,我要么贪食惩罚,要么我没有生命,但我编写了一个脚本,在问Ubuntu上回答一个问题,作为在给定目录中选择随机MP3文件并在所选的指定播放器中播放该文件的解决方案。。我不太好意思分享这一点,因为我知道这不是我最好的工作,而且几乎任何事情都依赖用户的输入。

脚本设计为传递用户想要使用的媒体播放器的可执行名称,并选择要在该播放器中播放的随机MP3文件。这里有一个小级别的邪恶,因为执行这个脚本的人必须指定一个媒体播放器。它还假设它位于基于Linux的系统上的用户的/home/$USER/Music目录中,因此要使用另一个dir,必须指定它。

任何你想给我的改进,请放心。不过,我知道这很管用。主要担心的是,我是否在任何地方脱轨并做了坏事。

randommp3.py (或,如果你想要漂亮):

代码语言:javascript
复制
#!/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)
EN

回答 1

Code Review用户

回答已采纳

发布于 2017-03-03 02:57:38

我将改进以下几点:

  • 将解析参数部分移到单独的函数(提取法)中
  • 在多行字符串常量中定义描述和帮助
  • 使用os.path.join()加入path组件也有助于避免担心拖尾斜杠。
  • 按字母顺序订购导入(PEP8 8参考)

改进后的代码:

代码语言:javascript
复制
#!/usr/bin/python
import argparse
import getpass
import glob
import os
import random
import subprocess as sp


DESCRIPTION = "Open a random MP3 in the player of choice, or the default player"
DIRECTORY_ARGUMENT_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.
"""
PLAYER_ARGUMENT_HELP = """
The executable name of the media player to open the MP3 with. 
If none specified, uses the system default player.
"""


def parse_args():
    """Parses command-line arguments and returns argparse arguments."""
    user_home_directory = os.path.join('/home', getpass.getuser())
    default_music_directory = os.path.join(user_home_directory, 'Music')

    parser = argparse.ArgumentParser(description=DESCRIPTION, add_help=True)
    parser.add_argument('--dir', '--directory', '--music-dir',
                        dest='dirpath', type=str, default=default_music_directory, required=False,
                        help=DIRECTORY_ARGUMENT_HELP)
    parser.add_argument('player', type=str, help=PLAYER_ARGUMENT_HELP)
    return parser.parse_args()


if __name__ == "__main__":
    args = parse_args()

    # Go to the directory your music is in.
    os.chdir(args.dirpath)
    mp3s = glob.glob('*.mp3')

    # Actually open the MP3 file, and /dev/null to suppress output messages from the process.
    DEV_NULL = open(os.devnull, 'w')
    execpath = [args.player, os.path.join(args.dirpath, random.choice(mp3s))]
    sp.Popen(execpath, stdout=DEV_NULL, stderr=DEV_NULL)

请注意,如果您使用的是Python3.x,那么DEVNULL可能是从subprocess模块

代码语言:javascript
复制
from subprocess import DEVNULL 
票数 4
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/156764

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档