当前位置: 首页>>代码示例>>Python>>正文


Python parsers.DurationParser类代码示例

本文整理汇总了Python中isodatetime.parsers.DurationParser的典型用法代码示例。如果您正苦于以下问题:Python DurationParser类的具体用法?Python DurationParser怎么用?Python DurationParser使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了DurationParser类的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _coerce_cycleinterval

def _coerce_cycleinterval(value, keys, _):
    """Coerce value to a cycle interval."""
    if not value:
        return None
    value = _strip_and_unquote(keys, value)
    if value.isdigit():
        # Old runahead limit format.
        set_syntax_version(VERSION_PREV,
                           "integer interval for %s" % itemstr(
                               keys[:-1], keys[-1], value))
        return value
    if REC_INTEGER_INTERVAL.match(value):
        # New integer cycling format.
        set_syntax_version(VERSION_NEW,
                           "integer interval for %s" % itemstr(
                               keys[:-1], keys[-1], value))
        return value
    parser = DurationParser()
    try:
        parser.parse(value)
    except ValueError:
        raise IllegalValueError("interval", keys, value)
    set_syntax_version(VERSION_NEW,
                       "ISO 8601 interval for %s" % itemstr(
                           keys[:-1], keys[-1], value))
    return value
开发者ID:oliver-sanders,项目名称:cylc,代码行数:26,代码来源:suite.py

示例2: coerce_interval

 def coerce_interval(self, value, keys):
     """Coerce an ISO 8601 interval (or number: back-comp) into seconds."""
     value = self.strip_and_unquote(keys, value)
     if not value:
         # Allow explicit empty values.
         return None
     try:
         interval = DurationParser().parse(value)
     except ValueError:
         raise IllegalValueError("ISO 8601 interval", keys, value)
     days, seconds = interval.get_days_and_seconds()
     return DurationFloat(
         days * Calendar.default().SECONDS_IN_DAY + seconds)
开发者ID:dpmatthews,项目名称:cylc,代码行数:13,代码来源:cfgvalidate.py

示例3: __init__

    def __init__(self, parse_format=None, utc_mode=False, calendar_mode=None,
                 ref_point_str=None):
        """Constructor.

        parse_format -- If specified, parse with the specified format.
                        Otherwise, parse with one of the format strings in
                        self.PARSE_FORMATS. The format should be a string
                        compatible to strptime(3).

        utc_mode -- If True, parse/print in UTC mode rather than local or
                    other timezones.

        calendar_mode -- Set calendar mode, for isodatetime.data.Calendar.

        ref_point_str -- Set the reference time point for operations.
                         If not specified, operations use current date time.

        """
        self.parse_formats = self.PARSE_FORMATS
        self.custom_parse_format = parse_format
        self.utc_mode = utc_mode
        if self.utc_mode:
            assumed_time_zone = (0, 0)
        else:
            assumed_time_zone = None

        self.set_calendar_mode(calendar_mode)

        self.time_point_dumper = TimePointDumper()
        self.time_point_parser = TimePointParser(
            assumed_time_zone=assumed_time_zone)
        self.duration_parser = DurationParser()

        self.ref_point_str = ref_point_str
开发者ID:lexual,项目名称:rose,代码行数:34,代码来源:date.py

示例4: coerce_cycle_point

 def coerce_cycle_point(cls, value, keys):
     """Coerce value to a cycle point."""
     if not value:
         return None
     value = cls.strip_and_unquote(keys, value)
     if value == 'now':
         # Handle this later in config.py when the suite UTC mode is known.
         return value
     if "next" in value or "previous" in value:
         # Handle this later, as for "now".
         return value
     if value.isdigit():
         # Could be an old date-time cycle point format, or integer format.
         return value
     if "P" not in value and (
             value.startswith('-') or value.startswith('+')):
         # We don't know the value given for num expanded year digits...
         for i in range(1, 101):
             try:
                 TimePointParser(num_expanded_year_digits=i).parse(value)
             except ValueError:
                 continue
             return value
         raise IllegalValueError('cycle point', keys, value)
     if "P" in value:
         # ICP is an offset
         parser = DurationParser()
         try:
             if value.startswith("-"):
                 # parser doesn't allow negative duration with this setup?
                 parser.parse(value[1:])
             else:
                 parser.parse(value)
             return value
         except ValueError:
             raise IllegalValueError("cycle point", keys, value)
     try:
         TimePointParser().parse(value)
     except ValueError:
         raise IllegalValueError('cycle point', keys, value)
     return value
开发者ID:dpmatthews,项目名称:cylc,代码行数:41,代码来源:cfgvalidate.py

示例5: __init__

 def __init__(self, *args, **kwargs):
     Runner.__init__(self, *args, **kwargs)
     path = os.path.dirname(os.path.dirname(sys.modules["rose"].__file__))
     self.builtins_manager = SchemeHandlersManager(
         [path], "rose.apps", ["run"], None, *args, **kwargs)
     self.duration_parser = DurationParser()
开发者ID:ScottWales,项目名称:rose,代码行数:6,代码来源:app_run.py

示例6: AppRunner

class AppRunner(Runner):

    """Invoke a Rose application."""

    OLD_DURATION_UNITS = {"h": 3600, "m": 60, "s": 1}
    NAME = "app"
    OPTIONS = ["app_mode", "command_key", "conf_dir", "defines",
               "install_only_mode", "new_mode", "no_overwrite_mode",
               "opt_conf_keys"]

    def __init__(self, *args, **kwargs):
        Runner.__init__(self, *args, **kwargs)
        path = os.path.dirname(os.path.dirname(sys.modules["rose"].__file__))
        self.builtins_manager = SchemeHandlersManager(
            [path], "rose.apps", ["run"], None, *args, **kwargs)
        self.duration_parser = DurationParser()

    def run_impl(self, opts, args, uuid, work_files):
        """The actual logic for a run."""

        # Preparation.
        conf_tree = self.config_load(opts)
        self._prep(conf_tree, opts)
        self._poll(conf_tree)

        # Run the application or the command.
        app_mode = conf_tree.node.get_value(["mode"])
        if app_mode is None:
            app_mode = opts.app_mode
        if app_mode in [None, "command"]:
            return self._command(conf_tree, opts, args)
        else:
            builtin_app = self.builtins_manager.get_handler(app_mode)
            if builtin_app is None:
                raise UnknownBuiltinAppError(app_mode)
            return builtin_app.run(self, conf_tree, opts, args, uuid,
                                   work_files)

    def _poll(self, conf_tree):
        """Poll for prerequisites of applications."""
        # Poll configuration
        poll_test = conf_tree.node.get_value(["poll", "test"])
        poll_all_files_value = conf_tree.node.get_value(["poll", "all-files"])
        poll_all_files = []
        if poll_all_files_value:
            try:
                poll_all_files = shlex.split(
                    env_var_process(poll_all_files_value))
            except UnboundEnvironmentVariableError as exc:
                raise ConfigValueError(["poll", "all-files"],
                                       poll_all_files_value, exc)
        poll_any_files_value = conf_tree.node.get_value(["poll", "any-files"])
        poll_any_files = []
        if poll_any_files_value:
            try:
                poll_any_files = shlex.split(
                    env_var_process(poll_any_files_value))
            except UnboundEnvironmentVariableError as exc:
                raise ConfigValueError(["poll", "any-files"],
                                       poll_any_files_value, exc)
        poll_file_test = None
        if poll_all_files or poll_any_files:
            poll_file_test = conf_tree.node.get_value(["poll", "file-test"])
            if poll_file_test and "{}" not in poll_file_test:
                raise ConfigValueError(["poll", "file-test"], poll_file_test,
                                       ConfigValueError.SYNTAX)
        poll_delays = []
        if poll_test or poll_all_files or poll_any_files:
            # Parse something like this: delays=10,4*PT30S,PT2M30S,2*PT1H
            # R*DURATION: repeat the value R times
            conf_keys = ["poll", "delays"]
            poll_delays_value = conf_tree.node.get_value(
                conf_keys, default="").strip()
            if poll_delays_value:
                is_legacy0 = None
                for item in poll_delays_value.split(","):
                    value = item.strip()
                    repeat = 1
                    if "*" in value:
                        repeat, value = value.split("*", 1)
                        try:
                            repeat = int(repeat)
                        except ValueError as exc:
                            raise ConfigValueError(conf_keys,
                                                   poll_delays_value,
                                                   ConfigValueError.SYNTAX)
                    try:
                        value = self.duration_parser.parse(value).get_seconds()
                        is_legacy = False
                    except ISO8601SyntaxError:
                        # Legacy mode: nnnU
                        # nnn is a float, U is the unit
                        # No unit or s: seconds
                        # m: minutes
                        # h: hours
                        unit = None
                        if value[-1].lower() in self.OLD_DURATION_UNITS:
                            unit = self.OLD_DURATION_UNITS[value[-1].lower()]
                            value = value[:-1]
                        try:
#.........这里部分代码省略.........
开发者ID:ScottWales,项目名称:rose,代码行数:101,代码来源:app_run.py

示例7: RoseDateTimeOperator

class RoseDateTimeOperator(object):

    """A class to parse and print date string with an offset."""

    CURRENT_TIME_DUMP_FORMAT = u"CCYY-MM-DDThh:mm:ss+hh:mm"
    CURRENT_TIME_DUMP_FORMAT_Z = u"CCYY-MM-DDThh:mm:ssZ"

    NEGATIVE = "-"

    # strptime formats and their compatibility with the ISO 8601 parser.
    PARSE_FORMATS = [
        ("%a %b %d %H:%M:%S %Y", True),     # ctime
        ("%a %b %d %H:%M:%S %Z %Y", True),  # Unix "date"
        ("%Y-%m-%dT%H:%M:%S", False),       # ISO8601, extended
        ("%Y%m%dT%H%M%S", False),           # ISO8601, basic
        ("%Y%m%d%H", False)                 # Cylc (current)
    ]

    REC_OFFSET = re.compile(r"""\A[\+\-]?(?:\d+[wdhms])+\Z""", re.I)

    REC_OFFSET_FIND = re.compile(r"""(?P<num>\d+)(?P<unit>[wdhms])""")

    STR_NOW = "now"
    STR_REF = "ref"

    TASK_CYCLE_TIME_ENV = "ROSE_TASK_CYCLE_TIME"

    UNITS = {"w": "weeks",
             "d": "days",
             "h": "hours",
             "m": "minutes",
             "s": "seconds"}

    def __init__(self, parse_format=None, utc_mode=False, calendar_mode=None,
                 ref_point_str=None):
        """Constructor.

        parse_format -- If specified, parse with the specified format.
                        Otherwise, parse with one of the format strings in
                        self.PARSE_FORMATS. The format should be a string
                        compatible to strptime(3).

        utc_mode -- If True, parse/print in UTC mode rather than local or
                    other timezones.

        calendar_mode -- Set calendar mode, for isodatetime.data.Calendar.

        ref_point_str -- Set the reference time point for operations.
                         If not specified, operations use current date time.

        """
        self.parse_formats = self.PARSE_FORMATS
        self.custom_parse_format = parse_format
        self.utc_mode = utc_mode
        if self.utc_mode:
            assumed_time_zone = (0, 0)
        else:
            assumed_time_zone = None

        self.set_calendar_mode(calendar_mode)

        self.time_point_dumper = TimePointDumper()
        self.time_point_parser = TimePointParser(
            assumed_time_zone=assumed_time_zone)
        self.duration_parser = DurationParser()

        self.ref_point_str = ref_point_str

    def date_format(self, print_format, time_point=None):
        """Reformat time_point according to print_format.

        time_point -- The time point to format.
                      Otherwise, use ref date time.

        """
        if time_point is None:
            time_point = self.date_parse()[0]
        if print_format is None:
            return str(time_point)
        if "%" in print_format:
            try:
                return time_point.strftime(print_format)
            except ValueError:
                return self.get_datetime_strftime(time_point, print_format)
        return self.time_point_dumper.dump(time_point, print_format)

    def date_parse(self, time_point_str=None):
        """Parse time_point_str.

        Return (t, format) where t is a isodatetime.data.TimePoint object and
        format is the format that matches time_point_str.

        time_point_str -- The time point string to parse.
                          Otherwise, use ref time.

        """
        if time_point_str is None or time_point_str == self.STR_REF:
            time_point_str = self.ref_point_str
        if time_point_str is None or time_point_str == self.STR_NOW:
            time_point = get_timepoint_for_now()
#.........这里部分代码省略.........
开发者ID:lexual,项目名称:rose,代码行数:101,代码来源:date.py

示例8: ControlTree

class ControlTree(object):
    """Text Treeview suite control interface."""
    def __init__(self, cfg, updater, theme, dot_size, info_bar,
                 get_right_click_menu, log_colors, insert_task_popup):

        self.cfg = cfg
        self.updater = updater
        self.theme = theme
        self.dot_size = dot_size
        self.info_bar = info_bar
        self.get_right_click_menu = get_right_click_menu
        self.log_colors = log_colors
        self.insert_task_popup = insert_task_popup
        self.interval_parser = DurationParser()

        self.gcapture_windows = []

        self.ttree_paths = {}  # Cache dict of tree paths & states, names.

    def get_control_widgets(self):
        main_box = gtk.VBox()
        main_box.pack_start(self.treeview_widgets(), expand=True, fill=True)

        self.t = TreeUpdater(
            self.cfg, self.updater, self.ttreeview, self.ttree_paths,
            self.info_bar, self.theme, self.dot_size
        )
        self.t.start()
        return main_box

    def toggle_grouping(self, toggle_item):
        """Toggle grouping by visualisation families."""
        group_on = toggle_item.get_active()
        if group_on == self.t.should_group_families:
            return False
        if group_on:
            if "text" in self.cfg.ungrouped_views:
                self.cfg.ungrouped_views.remove("text")
        elif "text" not in self.cfg.ungrouped_views:
            self.cfg.ungrouped_views.append("text")
        self.t.should_group_families = group_on
        if isinstance(toggle_item, gtk.ToggleToolButton):
            if group_on:
                tip_text = "Tree View - Click to ungroup families"
            else:
                tip_text = "Tree View - Click to group tasks by families"
            self._set_tooltip(toggle_item, tip_text)
            self.group_menu_item.set_active(group_on)
        else:
            if toggle_item != self.group_menu_item:
                self.group_menu_item.set_active(group_on)
            self.group_toolbutton.set_active(group_on)
        self.t.update_gui()
        return False

    def stop(self):
        self.t.quit = True

    def toggle_autoexpand(self, w):
        self.t.autoexpand = not self.t.autoexpand

    def treeview_widgets(self):
        self.sort_col_num = 0
        self.ttreestore = gtk.TreeStore(
            str, str, str, str, str, str, str, str, str, str, str,
            gtk.gdk.Pixbuf, int)
        self.ttreeview = gtk.TreeView()
        self.ttreeview.set_rules_hint(True)
        # TODO - REMOVE FILTER HERE?
        self.tmodelfilter = self.ttreestore.filter_new()
        self.tmodelsort = gtk.TreeModelSort(self.tmodelfilter)
        self.ttreeview.set_model(self.tmodelsort)

        ts = self.ttreeview.get_selection()
        ts.set_mode(gtk.SELECTION_SINGLE)

        self.ttreeview.connect(
            'button_press_event', self.on_treeview_button_pressed)
        headings = [
            None, 'task', 'state', 'host', 'job system', 'job ID', 'T-submit',
            'T-start', 'T-finish', 'dT-mean', 'latest message',
        ]

        for n in range(1, len(headings)):
            # Skip first column (cycle point)
            tvc = gtk.TreeViewColumn(headings[n])
            if n == 1:
                crp = gtk.CellRendererPixbuf()
                tvc.pack_start(crp, False)
                tvc.set_attributes(crp, pixbuf=11)
            if n == 8:
                # Pack in progress and text cell renderers.
                prog_cr = gtk.CellRendererProgress()
                tvc.pack_start(prog_cr, True)
                tvc.set_cell_data_func(prog_cr, self._set_cell_text_time, n)
            cr = gtk.CellRendererText()
            tvc.pack_start(cr, True)
            if n == 6 or n == 7 or n == 8:
                tvc.set_cell_data_func(cr, self._set_cell_text_time, n)
            else:
#.........这里部分代码省略.........
开发者ID:kaday,项目名称:cylc,代码行数:101,代码来源:view_tree.py


注:本文中的isodatetime.parsers.DurationParser类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。