Example #1
0
    def _print(self, unicode_text):
        assert is_unicode(unicode_text), 'Text must be unicode: %s' % unicode_text

        try:
            print_safe(unicode_text, self.encoding, output=self._output, errors='strict', newline='')
        except (LookupError, UnicodeError):
            raise EncodingError('Failed to print menu: lang=%s, encoding=%s' % (self.lang, self.encoding))
Example #2
0
def main(stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr):
    """
    Main function
    """

    setting = Setting(stdin=stdin, stdout=stdout,
                      stderr=stderr).parse_args(sys.argv)
    printer = Printer(setting.i18n, setting.stdin, setting.stdout,
                      setting.stderr)
    speaker = Speaker(setting.say_enabled,
                      setting.say_cmd,
                      setting.say_countdown_sec,
                      setting.say_periodic_min,
                      setting.say_specific_min,
                      i18n=setting.i18n,
                      stdin=setting.stdin,
                      stdout=setting.stdout,
                      stderr=setting.stderr)

    if not speaker.verify():
        print_safe('\nError: "say" command is not working correctly.',
                   output=stdout)
        sys.exit(2)

    try:
        CountdownTimer(setting.timer_sec, printer, speaker).loop()
    except KeyboardInterrupt:
        pass
Example #3
0
    def _eval_command_with_cache(self, cmdline, expire):
        path = self._eval_cache_path(cmdline)

        # read cache
        is_readable = not self.clear_cache and os.path.exists(path) and (
            time.time() - os.path.getmtime(path)) < expire
        if is_readable:
            print_safe('Reading eval cache: %s' % path,
                       self.encoding,
                       output=self.stdout)
            with open(path, 'rb') as f:
                return f.read()

        # execute command
        data = self._eval_command(cmdline)

        # write cache
        print_safe('Writing eval cache: %s' % path,
                   self.encoding,
                   output=self.stdout)

        # make parent directory
        if not os.path.exists(os.path.dirname(path)):
            os.makedirs(os.path.dirname(path))

        with open(self._eval_cache_path(cmdline), 'wb') as f:
            f.write(data)
        return data
Example #4
0
 def run(self):
     service = GoogleCalendarService(self.credential_path)
     event_id = service.insert_event(self.calendar_id, self.event)
     self.event.event_id = event_id
     print_safe(MSG_EVENT_CREATED % {
         'event': self.event.to_long_summary(),
         'event_id': event_id
     })
    def run(self):
        # fetch events
        service = GoogleCalendarService(self.credential_path)
        events = service.list_events(self.calendar_id, self.start_time, self.start_time + self.duration)

        # print the result
        print_safe(self._make_output(events))
        return 0
Example #6
0
    def _eval_command(self, cmdline):
        """
        :param cmdline:
        :return: encoded binary
        """

        # return code and stderr are ignored
        print_safe('Executing: %s' % cmdline, self.encoding, output=self.stdout)
        return capture_command(cmdline, shell=True, cwd=self.work_dir, cmd_encoding=self.encoding)[1]
Example #7
0
    def run(self):
        # fetch events
        service = GoogleCalendarService(self.credential_path)
        events = service.list_events(self.calendar_id, self.start_time,
                                     self.start_time + self.duration)

        # print the result
        print_safe(self._make_output(events))
        return 0
Example #8
0
    def _print(self, unicode_text):
        assert is_unicode(
            unicode_text), 'Text must be unicode: %s' % unicode_text

        try:
            print_safe(unicode_text,
                       self.encoding,
                       output=self._output,
                       errors='strict',
                       newline='')
        except (LookupError, UnicodeError):
            raise EncodingError('Failed to print menu: lang=%s, encoding=%s' %
                                (self.lang, self.encoding))
Example #9
0
    def _eval_command(self, cmdline):
        """
        :param cmdline:
        :return: encoded binary
        """

        # return code and stderr are ignored
        print_safe('Executing: %s' % cmdline,
                   self.encoding,
                   output=self.stdout)
        return capture_command(cmdline,
                               shell=True,
                               cwd=self.work_dir,
                               cmd_encoding=self.encoding)[1]
Example #10
0
    def test_print_safe(self):
        self.assertOutput('あいう\n', '',
                          lambda: io.print_safe('あいう', output=sys.stdout))
        self.assertOutput(
            'あいう\n', '',
            lambda: io.print_safe('あいう', encoding='sjis', output=sys.stdout),
            'sjis')

        # When a character failed to encode, it will be ignored.
        self.assertOutput(
            '\n', '',
            lambda: io.print_safe('あいう', encoding='ascii', output=sys.stdout))

        # When the string is already bytes, decode then encode with the specific encoding.
        self.assertOutput(
            'あいう\n', '', lambda: io.print_safe(
                'あいう'.encode('utf-8'), encoding='utf-8', output=sys.stdout))
        self.assertOutput(
            '\n', '', lambda: io.print_safe(
                'あいう'.encode('sjis'), encoding='utf-8', output=sys.stdout),
            'sjis')
        self.assertOutput(
            '\n', '', lambda: io.print_safe(
                'あいう'.encode('utf-8'), encoding='ascii', output=sys.stdout))
        self.assertOutput(
            'あいう\n', '', lambda: io.print_safe(
                'あいう'.encode('sjis'), encoding='sjis', output=sys.stdout),
            'sjis')
        self.assertOutput(
            '\n', '', lambda: io.print_safe(
                'あいう'.encode('sjis'), encoding='ascii', output=sys.stdout),
            'sjis')
    def run(self):
        assert not os.path.exists(self.credential_path), 'Credential file already exists: %s' % self.credential_path

        scopes = [SCOPE_READ_ONLY if self.read_only else SCOPE_READ_WRITE]
        flow = oauth2client.client.flow_from_clientsecrets(self.secret_path, scopes)
        store = oauth2client.file.Storage(self.credential_path)
        args = ['--noauth_local_webserver'] if self.no_browser else []
        flags = argparse.ArgumentParser(parents=[oauth2client.tools.argparser]).parse_args(args)

        parent_dir = os.path.dirname(self.credential_path)
        if not os.path.exists(parent_dir):
            os.makedirs(parent_dir)
        credentials = oauth2client.tools.run_flow(flow, store, flags)
        assert credentials is not None and not credentials.invalid, 'Failed to create credential file.'

        print_safe('Saved credential file: %s' % self.credential_path)
        return 0
Example #12
0
def main():
    """
    Main function
    """

    setting = None
    try:
        setting = Setting().parse_args(sys.argv)
        return_code = setting.operation.run()
    except KeyboardInterrupt:
        return_code = 3
    except Exception as e:
        if setting is None or setting.debug:
            import traceback
            traceback.print_exc()
        else:
            print_safe('%s: %s' % (e.__class__.__name__, e))
        return_code = 2
    return return_code
    def run(self):
        assert not os.path.exists(
            self.credential_path
        ), 'Credential file already exists: %s' % self.credential_path

        scopes = [SCOPE_READ_ONLY if self.read_only else SCOPE_READ_WRITE]
        flow = oauth2client.client.flow_from_clientsecrets(
            self.secret_path, scopes)
        store = oauth2client.file.Storage(self.credential_path)
        args = ['--noauth_local_webserver'] if self.no_browser else []
        flags = argparse.ArgumentParser(
            parents=[oauth2client.tools.argparser]).parse_args(args)

        parent_dir = os.path.dirname(self.credential_path)
        if not os.path.exists(parent_dir):
            os.makedirs(parent_dir)
        credentials = oauth2client.tools.run_flow(flow, store, flags)
        assert credentials is not None and not credentials.invalid, 'Failed to create credential file.'

        print_safe('Saved credential file: %s' % self.credential_path)
        return 0
Example #14
0
    def _eval_command_with_cache(self, cmdline, expire):
        path = self._eval_cache_path(cmdline)

        # read cache
        is_readable = not self.clear_cache and os.path.exists(path) and (time.time() - os.path.getmtime(path)) < expire
        if is_readable:
            print_safe('Reading eval cache: %s' % path, self.encoding, output=self.stdout)
            with open(path, 'rb') as f:
                return f.read()

        # execute command
        data = self._eval_command(cmdline)

        # write cache
        print_safe('Writing eval cache: %s' % path, self.encoding, output=self.stdout)

        # make parent directory
        if not os.path.exists(os.path.dirname(path)):
            os.makedirs(os.path.dirname(path))

        with open(self._eval_cache_path(cmdline), 'wb') as f:
            f.write(data)
        return data
Example #15
0
    def test_print_safe(self):
        self.assertOutput('あいう\n', '',
                          lambda: io.print_safe('あいう', output=sys.stdout))
        self.assertOutput('あいう\n', '',
                          lambda: io.print_safe('あいう', encoding='sjis', output=sys.stdout), 'sjis')

        # When a character failed to encode, it will be ignored.
        self.assertOutput('\n', '',
                          lambda: io.print_safe('あいう', encoding='ascii', output=sys.stdout))

        # When the string is already bytes, decode then encode with the specific encoding.
        self.assertOutput('あいう\n', '',
                          lambda: io.print_safe('あいう'.encode('utf-8'), encoding='utf-8', output=sys.stdout))
        self.assertOutput('\n', '',
                          lambda: io.print_safe('あいう'.encode('sjis'), encoding='utf-8', output=sys.stdout),
                          'sjis')
        self.assertOutput('\n', '',
                          lambda: io.print_safe('あいう'.encode('utf-8'), encoding='ascii', output=sys.stdout))
        self.assertOutput('あいう\n', '',
                          lambda: io.print_safe('あいう'.encode('sjis'), encoding='sjis', output=sys.stdout),
                          'sjis')
        self.assertOutput('\n', '',
                          lambda: io.print_safe('あいう'.encode('sjis'), encoding='ascii', output=sys.stdout),
                          'sjis')
 def run(self):
     service = GoogleCalendarService(self.credential_path)
     service.insert_event(self.calendar_id, self.event)
     print_safe(MSG_EVENT_CREATED % {'event': self.event.to_long_summary()})
Example #17
0
    def load(self, is_command, path_or_url_or_cmdline, eval_expire=None):
        """
        Load data from one file, url or command line, then store to a dict.

        :param is_command: True if using command line output
        :param path_or_url_or_cmdline:
        :param eval_expire: seconds to read
        :return: dict representation of data
        """
        assert path_or_url_or_cmdline

        # normalize file path
        is_url = self.is_url(path_or_url_or_cmdline)
        if not is_command and not is_url:
            if self.work_dir is not None and not os.path.isabs(
                    path_or_url_or_cmdline):
                path_or_url_or_cmdline = os.path.join(self.work_dir,
                                                      path_or_url_or_cmdline)

        # if already loaded, use cache data
        c = self.cache.get((is_command, path_or_url_or_cmdline))
        if c is not None:
            return c

        try:
            if is_command:
                # execute command
                if eval_expire is None:
                    data = self._eval_command(path_or_url_or_cmdline)
                else:
                    # if eval_expire is defined, check the cache on disk
                    data = self._eval_command_with_cache(
                        path_or_url_or_cmdline, eval_expire)
            elif self.is_url(path_or_url_or_cmdline):
                # read from URL
                print_safe('Reading from URL: %s' % path_or_url_or_cmdline,
                           self.encoding,
                           output=self.stdout)
                data = urlopen(path_or_url_or_cmdline).read()
            else:
                # read from file as bytes
                print_safe('Reading file: %s' % path_or_url_or_cmdline,
                           self.encoding,
                           output=self.stdout)
                with open(path_or_url_or_cmdline, 'rb') as f:
                    data = f.read()

            # decode string with fallback
            data_str = unicode_decode(data, [self.encoding, 'utf-8'])

            # apply jinja2 template rendering
            try:
                data_str = Environment().from_string(data_str).render()
            finally:
                pass

            # load as YAML string
            menu = yaml.load(data_str)

            # update cache data (Note: cache property is mutable!)
            self.cache[(is_command, path_or_url_or_cmdline)] = menu
        except IOError:
            raise ConfigError(path_or_url_or_cmdline, 'Failed to open.')
        except UnicodeDecodeError:
            raise EncodingError('Failed to decode with %s: %s' %
                                (self.encoding, path_or_url_or_cmdline))
        except yaml.YAMLError as e:
            raise ConfigError(path_or_url_or_cmdline,
                              'YAML format error: %s' % to_unicode(str(e)))
        return menu
Example #18
0
 def print_time(self, remain_sec):
     print_safe('\r%02d:%02d ' % (remain_sec // 60, remain_sec % 60),
                output=self.stdout,
                newline='')
Example #19
0
 def terminate(self):
     print_safe('', output=self.stdout)
Example #20
0
    def load(self, is_command, path_or_url_or_cmdline, eval_expire=None):
        """
        Load data from one file, url or command line, then store to a dict.

        :param is_command: True if using command line output
        :param path_or_url_or_cmdline:
        :param eval_expire: seconds to read
        :return: dict representation of data
        """
        assert path_or_url_or_cmdline

        # normalize file path
        is_url = self.is_url(path_or_url_or_cmdline)
        if not is_command and not is_url:
            if self.work_dir is not None and not os.path.isabs(path_or_url_or_cmdline):
                path_or_url_or_cmdline = os.path.join(self.work_dir, path_or_url_or_cmdline)

        # if already loaded, use cache data
        c = self.cache.get((is_command, path_or_url_or_cmdline))
        if c is not None:
            return c

        try:
            if is_command:
                # execute command
                if eval_expire is None:
                    data = self._eval_command(path_or_url_or_cmdline)
                else:
                    # if eval_expire is defined, check the cache on disk
                    data = self._eval_command_with_cache(path_or_url_or_cmdline, eval_expire)
            elif self.is_url(path_or_url_or_cmdline):
                # read from URL
                print_safe('Reading from URL: %s' % path_or_url_or_cmdline, self.encoding, output=self.stdout)
                data = urlopen(path_or_url_or_cmdline).read()
            else:
                # read from file as bytes
                print_safe('Reading file: %s' % path_or_url_or_cmdline, self.encoding, output=self.stdout)
                with open(path_or_url_or_cmdline, 'rb') as f:
                    data = f.read()

            # decode string with fallback
            data_str = unicode_decode(data, [self.encoding, 'utf-8'])

            # apply jinja2 template rendering
            try:
                data_str = Environment().from_string(data_str).render()
            finally:
                pass

            # load as YAML string
            menu = yaml.load(data_str)

            # update cache data (Note: cache property is mutable!)
            self.cache[(is_command, path_or_url_or_cmdline)] = menu
        except IOError:
            raise ConfigError(path_or_url_or_cmdline, 'Failed to open.')
        except UnicodeDecodeError:
            raise EncodingError('Failed to decode with %s: %s' % (self.encoding, path_or_url_or_cmdline))
        except yaml.YAMLError as e:
            raise ConfigError(path_or_url_or_cmdline, 'YAML format error: %s' % to_unicode(str(e)))
        return menu
Example #21
0
 def test_print_safe_error(self):
     self.assertRaisesRegexp(UnicodeEncodeError,
                             "'ascii' codec can't encode characters in position 0-2: ordinal not in range\(128\)",
                             lambda: io.print_safe('あいう', encoding='ascii', output=sys.stdout, errors='strict'))
Example #22
0
 def run(self):
     service = GoogleCalendarService(self.credential_path)
     service.delete_event(self.calendar_id, self.event_id)
     print_safe(MSG_EVENT_DELETED % {'event': self.event_id})
Example #23
0
 def run(self):
     parser.print_usage()
     if self.exception:
         print_safe('%s: %s' %
                    (self.exception.__class__.__name__, self.exception))
Example #24
0
 def run(self):
     parser.print_usage()
     if self.exception:
         print_safe('%s: %s' % (self.exception.__class__.__name__, self.exception))
Example #25
0
 def test_print_safe_error(self):
     self.assertRaisesRegexp(
         UnicodeEncodeError,
         "'ascii' codec can't encode characters in position 0-2: ordinal not in range\(128\)",
         lambda: io.print_safe(
             'あいう', encoding='ascii', output=sys.stdout, errors='strict'))