Esempio n. 1
0
def control(command, arg=None, ignore_error=False):
    """Sends command to the existing instance if possible and exits.

    Will print any response it gets to stdout.

    Does not return except if ignore_error is True and sending
    the command failed.
    """

    if not is_running():
        if ignore_error:
            return
        exit_(_("Quod Libet is not running (add '--run' to start it)"),
              notify_startup=True)
        return

    message = command
    if arg is not None:
        message += " " + arg

    try:
        response = Remote.send_message(message)
    except RemoteError as e:
        if ignore_error:
            return
        exit_(str(e), notify_startup=True)
    else:
        if response is not None:
            print_(response, end="")
        exit_(notify_startup=True)
Esempio n. 2
0
def control(command, arg=None, ignore_error=False):
    """Sends command to the existing instance if possible and exits.

    Will print any response it gets to stdout.

    Does not return except if ignore_error is True and sending
    the command failed.
    """

    if not is_running():
        if ignore_error:
            return
        exit_(_("Quod Libet is not running (add '--run' to start it)"),
              notify_startup=True)
        return

    message = command
    if arg is not None:
        message += " " + arg

    try:
        response = Remote.send_message(message)
    except RemoteError as e:
        if ignore_error:
            return
        exit_(str(e), notify_startup=True)
    else:
        if response is not None:
            print_(response, end="")
        exit_(notify_startup=True)
Esempio n. 3
0
    def __request(self, line, raw=False, want_reply=True):
        """
        Send a request to the server, if connected, and return its response
        """
        line = line.strip()

        if not (self.is_connected or line.split()[0] == 'login'):
            print_d("Can't do '%s' - not connected" % line.split()[0], self)
            return None

        if self._debug:
            print_(">>>> \"%s\"" % line)
        try:
            self.telnet.write(line + "\n")
            if not want_reply:
                return None
            raw_response = self.telnet.read_until("\n").strip()
        except socket.error as e:
            print_w("Couldn't communicate with squeezebox (%s)" % e)
            self.failures += 1
            if self.failures >= self._MAX_FAILURES:
                print_w("Too many Squeezebox failures. Disconnecting")
                self.is_connected = False
            return None
        response = raw_response if raw else urllib.unquote(raw_response)
        if self._debug:
            print_("<<<< \"%s\"" % (response, ))
        return response[len(line) - 1:] if line.endswith("?")\
            else response[len(line) + 1:]
Esempio n. 4
0
def print_terse_table(rows, nicks, order):
    """Print a terse table"""

    for row in filter_table(rows, nicks, order):
        row = [r.replace("\\", "\\\\") for r in row]
        row = [r.replace(":", r"\:") for r in row]
        print_(":".join(row))
Esempio n. 5
0
    def _execute(self, options, args):
        if len(args) < 1:
            raise CommandError("Not enough arguments")

        pattern = options.pattern
        if pattern is None:
            pattern = "<artist~album~tracknumber~title>"

        self.log("Using pattern: %r" % pattern)

        try:
            pattern = parse.Pattern(pattern)
        except ValueError:
            raise CommandError("Invalid pattern: %r" % pattern)

        paths = args
        error = False
        for path in paths:
            try:
                print_(pattern % self.load_song(path))
            except CommandError:
                error = True

        if error:
            raise CommandError("One or more files failed to load.")
Esempio n. 6
0
    def __request(self, line, raw=False, want_reply=True):
        """
        Send a request to the server, if connected, and return its response
        """
        line = line.strip()

        if not (self.is_connected or line.split()[0] == 'login'):
            print_d("Can't do '%s' - not connected" % line.split()[0], self)
            return None

        if self._debug:
            print_(">>>> \"%s\"" % line)
        try:
            self.telnet.write(line + "\n")
            if not want_reply:
                return None
            raw_response = self.telnet.read_until("\n").strip()
        except socket.error as e:
            print_w("Couldn't communicate with squeezebox (%s)" % e)
            self.failures += 1
            if self.failures >= self._MAX_FAILURES:
                print_w("Too many Squeezebox failures. Disconnecting")
                self.is_connected = False
            return None
        response = raw_response if raw else urllib.unquote(raw_response)
        if self._debug:
            print_("<<<< \"%s\"" % (response,))
        return response[len(line) - 1:] if line.endswith("?")\
            else response[len(line) + 1:]
Esempio n. 7
0
 def printErrors(self):
     succ = self.testsRun - (len(self.errors) + len(self.failures))
     v = Colorise.bold("%3d" % succ)
     cv = Colorise.green(v) if succ == self.testsRun else Colorise.red(v)
     count = self.TEST_RESULTS_WIDTH - self.testsRun
     print_((" " * count) + cv)
     self.printErrorList('ERROR', self.errors)
     self.printErrorList('FAIL', self.failures)
Esempio n. 8
0
 def printErrors(self):
     succ = self.testsRun - (len(self.errors) + len(self.failures))
     v = Colorise.bold("%3d" % succ)
     cv = Colorise.green(v) if succ == self.testsRun else Colorise.red(v)
     count = self.TEST_RESULTS_WIDTH - self.testsRun
     print_((" " * count) + cv)
     self.printErrorList('ERROR', self.errors)
     self.printErrorList('FAIL', self.failures)
Esempio n. 9
0
def print_exc(limit=None, file=None):
    """A wrapper preventing crashes on broken pipes in print_exc."""
    if file is None:
        if PY2:
            file = sys.stderr
        else:
            file = sys.stderr.buffer
    print_(traceback.format_exc(limit=limit), output=file)
Esempio n. 10
0
def print_exc(limit=None, file=None):
    """A wrapper preventing crashes on broken pipes in print_exc."""
    if file is None:
        if PY2:
            file = sys.stderr
        else:
            file = sys.stderr.buffer
    print_(traceback.format_exc(limit=limit), output=file)
Esempio n. 11
0
 def __init__(self, test_name, num_tests, out=sys.stdout, failfast=False):
     super(Result, self).__init__()
     self.out = out
     self.failfast = failfast
     if hasattr(out, "flush"):
         out.flush()
     pref = "%s (%d): " % (Colorise.bold(test_name), num_tests)
     line = pref + " " * (self.TEST_NAME_WIDTH - len(test_name) - 7 - int(num_tests and log(num_tests, 10) or 0))
     print_(line, end="")
 def __init__(self, test_name, num_tests, out=sys.stdout):
     super(Result, self).__init__()
     self.out = out
     if hasattr(out, "flush"):
         out.flush()
     pref = '%s (%d): ' % (Colorise.bold(test_name), num_tests)
     line = pref + " " * (self.TEST_NAME_WIDTH - len(test_name) - 6 -
                          int(num_tests and log(num_tests, 10) or 0))
     print_(line, end="")
Esempio n. 13
0
 def exec_commands(*args):
     for cmd in cmds_todo:
         try:
             resp = cmd_registry.run(app, *cmd)
         except CommandError:
             pass
         else:
             if resp is not None:
                 print_(resp, end="")
Esempio n. 14
0
 def exec_commands(*args):
     for cmd in cmds_todo:
         try:
             resp = cmd_registry.run(app, *cmd)
         except CommandError:
             pass
         else:
             if resp is not None:
                 print_(resp, end="", flush=True)
Esempio n. 15
0
    def _execute(self, options, args):
        if len(args) < 1:
            raise CommandError(_("Not enough arguments"))
        elif len(args) > 1:
            raise CommandError(_("Too many arguments"))

        # load file
        path = args[0]
        song = self.load_song(path)

        # dump, sort and skip internal tags
        lines = sorted(song.to_dump().splitlines())
        print_("\n".join((l for l in lines if not l.startswith("~"))))
Esempio n. 16
0
def print_playing(fstring="<artist~album~tracknumber~title>"):
    import quodlibet
    from quodlibet.formats._audio import AudioFile
    from quodlibet.parse import Pattern
    from quodlibet import const

    try:
        text = open(const.CURRENT, "rb").read()
        song = AudioFile()
        song.from_dump(text)
        print_(Pattern(fstring).format(song))
        quodlibet.exit()
    except (OSError, IOError):
        print_(_("No song is currently playing."))
        quodlibet.exit(True)
Esempio n. 17
0
def _print_help(main_cmd, parser, file=None):
    """Print a short help list for all commands"""

    if file is None:
        file = sys.stdout

    parser.print_help(file=file)

    cl = ["", "Commands:"]
    for command in Command.COMMANDS:
        cl.append("   %-17s %s" % (command.NAME, command.DESCRIPTION))
    cl.append("")
    cl.append("See '%s help <command>' for more information "
              "on a specific command." % main_cmd)

    print_("\n".join(cl), file=file)
Esempio n. 18
0
def _print_help(main_cmd, parser, file=None):
    """Print a short help list for all commands"""

    if file is None:
        file = sys.stdout

    parser.print_help(file=file)

    cl = ["", "Commands:"]
    for command in Command.COMMANDS:
        cl.append("   %-17s %s" % (command.NAME, command.DESCRIPTION))
    cl.append("")
    cl.append("See '%s help <command>' for more information "
              "on a specific command." % main_cmd)

    print_("\n".join(cl), file)
Esempio n. 19
0
 def printErrorList(self, flavour, errors):
     for test, err in errors:
         print_(self.MAJOR_SEPARATOR)
         print_(Colorise.red("%s: %s" % (flavour, str(test))))
         print_(self.MINOR_SEPARATOR)
         # tracebacks can contain encoded paths, not sure
         # what the right fix is here, so use repr
         for line in err.splitlines():
             print_(repr(line)[1:-1])
Esempio n. 20
0
 def printErrorList(self, flavour, errors):
     for test, err in errors:
         print_(self.MAJOR_SEPARATOR)
         print_(Colorise.red("%s: %s" % (flavour, str(test))))
         print_(self.MINOR_SEPARATOR)
         # tracebacks can contain encoded paths, not sure
         # what the right fix is here, so use repr
         for line in err.splitlines():
             print_(repr(line)[1:-1])
Esempio n. 21
0
    def parse(self, args=None):
        if args is None:
            args = argv[1:]
        from getopt import getopt, GetoptError
        try:
            opts, args = getopt(args, self.__shorts(), self.__longs())
        except GetoptError as s:
            s = str(s)
            text = []
            if "not recognized" in s:
                text.append(
                    _("Option %r not recognized.") % s.split()[1])
            elif "requires argument" in s:
                text.append(
                    _("Option %r requires an argument.") % s.split()[1])
            elif "unique prefix" in s:
                text.append(
                    _("%r is not a unique prefix.") % s.split()[1])
            if "help" in self.__args:
                text.append(_("Try %s --help.") % argv[0])

            print_e("\n".join(text))
            raise SystemExit(True)
        else:
            transopts = {}
            for o, a in opts:
                if o.startswith("--"):
                    o = self.__translate_long.get(o[2:], o[2:])
                elif o.startswith("-"):
                    o = self.__translate_short.get(o[1:], o[1:])
                if o == "help":
                    print_(self.help())
                    raise SystemExit
                elif o == "version":
                    print_(self.version())
                    raise SystemExit
                elif o == "debug":
                    from quodlibet import const
                    const.DEBUG = True
                if self.__args[o]:
                    transopts[o] = a
                else:
                    transopts[o] = True

            return transopts, args
Esempio n. 22
0
    def parse(self, args=None):
        if args is None:
            args = argv[1:]
        from getopt import getopt, GetoptError
        try:
            opts, args = getopt(args, self.__shorts(), self.__longs())
        except GetoptError as s:
            s = str(s)
            text = []
            if "not recognized" in s:
                text.append(
                    _("Option %r not recognized.") % s.split()[1])
            elif "requires argument" in s:
                text.append(
                    _("Option %r requires an argument.") % s.split()[1])
            elif "unique prefix" in s:
                text.append(
                    _("%r is not a unique prefix.") % s.split()[1])
            if "help" in self.__args:
                text.append(_("Try %s --help.") % argv[0])

            print_e("\n".join(text))
            raise SystemExit(True)
        else:
            transopts = {}
            for o, a in opts:
                if o.startswith("--"):
                    o = self.__translate_long.get(o[2:], o[2:])
                elif o.startswith("-"):
                    o = self.__translate_short.get(o[1:], o[1:])
                if o == "help":
                    print_(self.help())
                    raise SystemExit
                elif o == "version":
                    print_(self.version())
                    raise SystemExit
                elif o == "debug":
                    from quodlibet import const
                    const.DEBUG = True
                if self.__args[o]:
                    transopts[o] = a
                else:
                    transopts[o] = True

            return transopts, args
Esempio n. 23
0
def print_table(rows, headers, nicks, order):
    """Print a fancy table"""

    rows.insert(0, headers)
    rows = filter_table(rows, nicks, order)
    if not rows:
        return

    widths = []
    for c in range(len(rows[0])):
        widths.append(max(map(lambda r: len(r[c]), rows)))

    seperator = " %s " % Colorise.gray("|")
    format_string = seperator.join(["%%-%ds" % w for w in widths])

    header = []
    for i, h in enumerate(rows.pop(0)):
        header.append(h.ljust(widths[i], " "))
    line_width = len("   ".join(header)) + 2
    header = [Colorise.bold(h) for h in header]
    header_line = " " + (" %s " % Colorise.gray("|")).join(header)

    print_(header_line.rstrip())
    print_(Colorise.gray("-" * line_width))

    for row in rows:
        print_(" " + (format_string % tuple(row)).rstrip())
Esempio n. 24
0
 def addFailure(self, test, err):
     unittest.TestResult.addFailure(self, test, err)
     print_(Colorise.red(self.CHAR_FAILURE), end="")
Esempio n. 25
0
    def log(self, text):
        """Print output if --verbose was passed"""

        if self.verbose:
            return print_(text, sys.stderr)
Esempio n. 26
0
                text.append(
                    _("%r is not a unique prefix.") % s.split()[1])
            if "help" in self.__args:
                text.append(_("Try %s --help.") % sys.argv[0])

            print_e("\n".join(text))
            raise SystemExit(True)
        else:
            transopts = {}
            for o, a in opts:
                if o.startswith("--"):
                    o = self.__translate_long.get(o[2:], o[2:])
                elif o.startswith("-"):
                    o = self.__translate_short.get(o[1:], o[1:])
                if o == "help":
                    print_(self.help())
                    raise SystemExit
                elif o == "version":
                    print_(self.version())
                    raise SystemExit
                elif o == "debug":
                    from quodlibet import const
                    const.DEBUG = True
                if self.__args[o]:
                    transopts[o] = a
                else:
                    transopts[o] = True

            return transopts, args

Esempio n. 27
0
 def addSuccess(self, test):
     unittest.TestResult.addSuccess(self, test)
     print_(Colorise.green(self.CHAR_SUCCESS), end="")
Esempio n. 28
0
 def addError(self, test, err):
     unittest.TestResult.addError(self, test, err)
     print_(Colorise.red(self.CHAR_ERROR), end="")
Esempio n. 29
0
 def addFailure(self, test, err):
     unittest.TestResult.addFailure(self, test, err)
     print_(Colorise.red(self.CHAR_FAILURE), end="")
Esempio n. 30
0
 def addError(self, test, err):
     unittest.TestResult.addError(self, test, err)
     print_(Colorise.red(self.CHAR_ERROR), end="")
Esempio n. 31
0
def main(argv):
    main_cmd = os.path.basename(argv[0])

    # the main optparser
    usage = "%s [--version] [--help] [--verbose] <command> [<args>]" % main_cmd
    parser = OptionParser(usage=usage)

    parser.remove_option("--help")
    parser.add_option("-h", "--help", action="store_true")
    parser.add_option("--version", action="store_true",
                      help="print version")
    parser.add_option("-v", "--verbose", action="store_true",
                      help="verbose output")

    # no args, print help (might change in the future)
    if len(argv) <= 1:
        _print_help(main_cmd, parser, file=sys.stderr)
        return 1

    # collect options for the main command and get the command offset
    offset = -1
    pre_command = []
    for i, a in enumerate(argv):
        if i == 0:
            continue
        elif a.startswith("-"):
            pre_command.append(a)
        else:
            offset = i
            break

    # parse the global options
    options = parser.parse_args(pre_command)[0]

    # --help somewhere
    if options.help:
        _print_help(main_cmd, parser)
        return 0

    # --version somewhere
    if options.version:
        print_("%s version %s" % (main_cmd, const.VERSION))
        return 0

    # no sub command followed, help to stderr
    if offset == -1:
        _print_help(main_cmd, parser, file=sys.stderr)
        return 1
    arg = argv[offset]

    # special case help and list all commands
    if arg == "help":
        # no command, list all commands
        if len(argv) == 2:
            _print_help(main_cmd, parser)
            return 0

    # get the right sub command and pass the remaining args
    for command in Command.COMMANDS:
        if command.NAME == arg:
            cmd = command(main_cmd, options)
            try:
                cmd.execute(argv[offset + 1:])
            except CommandError as e:
                print_(u"%s: %s" % (command.NAME, e), sys.stderr)
                return 1
            break
    else:
        print_(u"Unknown command '%s'. See '%s help'." % (arg, main_cmd),
               sys.stderr)
        return 1

    return 0
Esempio n. 32
0
def print_exc(limit=None, file=None):
    """A wrapper preventing crashes on broken pipes in print_exc."""
    if not file:
        file = sys.stderr
    print_(traceback.format_exc(limit=limit), output=file)
Esempio n. 33
0
            elif "unique prefix" in s:
                text.append(_("%r is not a unique prefix.") % s.split()[1])
            if "help" in self.__args:
                text.append(_("Try %s --help.") % sys.argv[0])

            print_e("\n".join(text))
            raise SystemExit(True)
        else:
            transopts = {}
            for o, a in opts:
                if o.startswith("--"):
                    o = self.__translate_long.get(o[2:], o[2:])
                elif o.startswith("-"):
                    o = self.__translate_short.get(o[1:], o[1:])
                if o == "help":
                    print_(self.help())
                    raise SystemExit
                elif o == "version":
                    print_(self.version())
                    raise SystemExit
                elif o == "debug":
                    from quodlibet import const
                    const.DEBUG = True
                if self.__args[o]:
                    transopts[o] = a
                else:
                    transopts[o] = True

            return transopts, args

Esempio n. 34
0
def print_exc(limit=None, file=None):
    """A wrapper preventing crashes on broken pipes in print_exc."""
    if not file:
        file = sys.stderr
    print_(traceback.format_exc(limit=limit), output=file)
Esempio n. 35
0
def main(argv):
    main_cmd = os.path.basename(argv[0])

    # the main optparser
    usage = "%s [--version] [--help] [--verbose] <command> [<args>]" % main_cmd
    parser = OptionParser(usage=usage)

    parser.remove_option("--help")
    parser.add_option("-h", "--help", action="store_true")
    parser.add_option("--version", action="store_true", help="print version")
    parser.add_option("-v",
                      "--verbose",
                      action="store_true",
                      help="verbose output")

    # no args, print help (might change in the future)
    if len(argv) <= 1:
        _print_help(main_cmd, parser, file=sys.stderr)
        return 1

    # collect options for the main command and get the command offset
    offset = -1
    pre_command = []
    for i, a in enumerate(argv):
        if i == 0:
            continue
        elif a.startswith("-"):
            pre_command.append(a)
        else:
            offset = i
            break

    # parse the global options
    options = parser.parse_args(pre_command)[0]

    # --help somewhere
    if options.help:
        _print_help(main_cmd, parser)
        return 0

    # --version somewhere
    if options.version:
        print_("%s version %s" % (main_cmd, const.VERSION))
        return 0

    # no sub command followed, help to stderr
    if offset == -1:
        _print_help(main_cmd, parser, file=sys.stderr)
        return 1
    arg = argv[offset]

    # special case help and list all commands
    if arg == "help":
        # no command, list all commands
        if len(argv) == 2:
            _print_help(main_cmd, parser)
            return 0

    # get the right sub command and pass the remaining args
    for command in Command.COMMANDS:
        if command.NAME == arg:
            cmd = command(main_cmd, options)
            try:
                cmd.execute(argv[offset + 1:])
            except CommandError as e:
                print_(u"%s: %s" % (command.NAME, e), file=sys.stderr)
                return 1
            break
    else:
        print_(u"Unknown command '%s'. See '%s help'." % (arg, main_cmd),
               file=sys.stderr)
        return 1

    return 0
Esempio n. 36
0
 def addSuccess(self, test):
     unittest.TestResult.addSuccess(self, test)
     print_(Colorise.green(self.CHAR_SUCCESS), end="")