コード例 #1
0
def main():
    # set the log level to WARNING avoid spamming the CLI while loading
    # subcommands
    # it will be restored to the desired one first thing in taurus_cmd()
    taurus.setLogLevel(taurus.Warning)

    # Add subcommands from the taurus_subcommands entry point
    for ep in pkg_resources.iter_entry_points('taurus.cli.subcommands'):
        try:
            subcommand = ep.load()
            taurus_cmd.add_command(subcommand)
        except Exception as e:
            # -----------------------------------------------------------
            # Use info instead of warning in case of nonimportable Qwt5
            # (e.g. when using py3 or Qt5) to avoid spam
            # This special case can be removed when taurus.qt.qtgui.qwt5
            # is moved to a separate plugin, since the entry point will
            # be registered only if the plugin is installed
            if ep.name == 'qwt5':
                taurus.info('Cannot add "%s" subcommand to taurus. Reason: %r',
                            ep.name, e)
                continue
            # -----------------------------------------------------------
            taurus.warning('Cannot add "%s" subcommand to taurus. Reason: %r',
                           ep.name, e)

    # launch the taurus command
    taurus_cmd()
コード例 #2
0
ファイル: qlogtable.py プロジェクト: cmft/taurus
def main():
    import taurus.qt.qtgui.application
    Application = taurus.qt.qtgui.application.TaurusApplication

    app = Application.instance()
    owns_app = app is None

    if owns_app:
        app = Application(app_name="Logging demo", app_version="1.0",
                          org_domain="Taurus", org_name="Taurus community")

    taurus.setLogLevel(taurus.Trace)
    taurus.disableLogOutput()
    w = QLoggingWidget()

    taurus.trace("trace message")
    taurus.debug("debug message")
    taurus.info("Hello world")
    taurus.warning("Warning message")
    taurus.error("error message")
    taurus.critical("critical message")
    w.setMinimumSize(1200, 600)
    w.show()
    app.exec_()
    w.stop_logging()
コード例 #3
0
def taurus_cmd(log_level, polling_period, serialization_mode, rconsole_port,
               default_formatter):
    """The main taurus command"""

    # set log level
    taurus.setLogLevel(getattr(taurus, log_level))

    # set polling period
    if polling_period is not None:
        taurus.changeDefaultPollingPeriod(polling_period)

    # set serialization mode
    if serialization_mode is not None:
        from taurus.core.taurusbasetypes import TaurusSerializationMode
        m = getattr(TaurusSerializationMode, serialization_mode)
        taurus.Manager().setSerializationMode(m)

    # enable the remote console port
    if rconsole_port is not None:
        try:
            import rfoo.utils.rconsole
            rfoo.utils.rconsole.spawn_server(port=rconsole_port)
            taurus.info(("rconsole started. " +
                         "You can connect to it by typing: rconsole -p %d"),
                        rconsole_port)
        except Exception as e:
            taurus.warning("Cannot spawn debugger. Reason: %s", e)

    # set the default formatter
    if default_formatter is not None:
        from taurus import tauruscustomsettings
        setattr(tauruscustomsettings, 'DEFAULT_FORMATTER', default_formatter)
コード例 #4
0
ファイル: test_expert.py プロジェクト: reszelaz/sardana
 def test_expert(self):
     CTRL_NAME = "unittestmotctrl01"
     MOT_NAME1 = "unittestmot01"
     MOT_NAME2 = "unittestmot02"
     try:
         self.macro_runs(macro_name="defctrl",
                         macro_params=["DummyMotorController", CTRL_NAME],
                         wait_timeout=1)
         self.macro_runs(macro_name="defm",
                         macro_params=[MOT_NAME1, CTRL_NAME, "1"],
                         wait_timeout=1)
         self.macro_runs(macro_name="defelem",
                         macro_params=[MOT_NAME2, CTRL_NAME, "2"],
                         wait_timeout=1)
         #     add test of renameelem when bug-471 is fixed
         #     https://sourceforge.net/p/sardana/tickets/471/
         #             self.macro_runs(macro_name="renameelem",
         #                             macro_params=[MOT_NAME1, MOT_NAME2],
         #                             wait_timeout=1)
         self.macro_runs(macro_name="udefelem",
                         macro_params=[MOT_NAME1, MOT_NAME2],
                         wait_timeout=1)
         self.macro_runs(macro_name="udefctrl",
                         macro_params=[CTRL_NAME],
                         wait_timeout=1)
     except Exception, e:
         import taurus
         taurus.warning("Your system may stay dirty due to an unexpected"
                        " exception during the test.")
         raise e
コード例 #5
0
ファイル: cli.py プロジェクト: dscran/taurus
def register_subcommands():
    """Discover and add subcommands to taurus_cmd"""

    # Add subcommands from the taurus_subcommands entry point
    for ep in pkg_resources.iter_entry_points("taurus.cli.subcommands"):
        try:
            subcommand = ep.load()
            taurus_cmd.add_command(subcommand)
        except Exception as e:
            # -----------------------------------------------------------
            # Use info instead of warning in case of nonimportable Qwt5
            # (e.g. when using py3 or Qt5) to avoid spam
            # This special case can be removed when taurus.qt.qtgui.qwt5
            # is moved to a separate plugin, since the entry point will
            # be registered only if the plugin is installed
            if ep.name == "qwt5":
                taurus.info(
                    'Cannot add "%s" subcommand to taurus. Reason: %r',
                    ep.name,
                    e,
                )
                continue
            # -----------------------------------------------------------
            taurus.warning('Cannot add "%s" subcommand to taurus. Reason: %r',
                           ep.name, e)
コード例 #6
0
ファイル: test_expert.py プロジェクト: cmft/sardana
    def test_expert(self):
        CTRL_NAME = "unittestmotctrl01"
        MOT_NAME1 = "unittestmot01"
        MOT_NAME2 = "unittestmot02"
        try:
            self.macro_runs(macro_name="defctrl",
                            macro_params=["DummyMotorController", CTRL_NAME],
                            wait_timeout=1)
            self.macro_runs(macro_name="defm",
                            macro_params=[MOT_NAME1, CTRL_NAME, "1"],
                            wait_timeout=1)
            self.macro_runs(macro_name="defelem",
                            macro_params=[MOT_NAME2, CTRL_NAME, "2"],
                            wait_timeout=1)
#     add test of renameelem when bug-471 is fixed
#     https://sourceforge.net/p/sardana/tickets/471/
#             self.macro_runs(macro_name="renameelem",
#                             macro_params=[MOT_NAME1, MOT_NAME2],
#                             wait_timeout=1)
            self.macro_runs(macro_name="udefelem",
                            macro_params=[MOT_NAME1, MOT_NAME2],
                            wait_timeout=1)
            self.macro_runs(macro_name="udefctrl",
                            macro_params = [CTRL_NAME],
                            wait_timeout=1)
        except Exception, e:
            import taurus
            taurus.warning("Your system may stay dirty due to an unexpected"
                           " exception during the test.")
            raise e
コード例 #7
0
def main():
    import taurus.qt.qtgui.application
    Application = taurus.qt.qtgui.application.TaurusApplication

    app = Application.instance()
    owns_app = app is None

    if owns_app:
        app = Application(app_name="Logging demo",
                          app_version="1.0",
                          org_domain="Taurus",
                          org_name="Taurus community")

    taurus.setLogLevel(taurus.Trace)
    taurus.disableLogOutput()
    w = QLoggingWidget()

    taurus.trace("trace message")
    taurus.debug("debug message")
    taurus.info("Hello world")
    taurus.warning("Warning message")
    taurus.error("error message")
    taurus.critical("critical message")
    w.setMinimumSize(1200, 600)
    w.show()
    app.exec_()
    w.stop_logging()
コード例 #8
0
ファイル: test_expert.py プロジェクト: rhomspuron/sardana
 def test_expert(self):
     CTRL_NAME = "unittestmotctrl01"
     MOT_NAME1 = "unittestmot01"
     MOT_NAME2 = "unittestmot02"
     try:
         self.macro_runs(macro_name="defctrl",
                         macro_params=["DummyMotorController", CTRL_NAME],
                         wait_timeout=1)
         self.macro_runs(macro_name="defelem",
                         macro_params=[MOT_NAME1, CTRL_NAME, "1"],
                         wait_timeout=1)
         self.macro_runs(macro_name="renameelem",
                         macro_params=[MOT_NAME1, MOT_NAME2],
                         wait_timeout=1)
         self.macro_runs(macro_name="defm",
                         macro_params=[MOT_NAME1, CTRL_NAME, "2"],
                         wait_timeout=1)
         self.macro_runs(macro_name="udefelem",
                         macro_params=[MOT_NAME1, MOT_NAME2],
                         wait_timeout=1)
         self.macro_runs(macro_name="udefctrl",
                         macro_params=[CTRL_NAME],
                         wait_timeout=1)
     except Exception, e:
         import taurus
         taurus.warning("Your system may stay dirty due to an unexpected"
                        " exception during the test.")
         raise e
コード例 #9
0
ファイル: taurusvalidator.py プロジェクト: jkrueger1/taurus
 def getUriGroups(self, name, strict=None):
     '''returns the named groups dictionary from the URI regexp matching.
     If strict is False, it also tries to match against the non-strict regexp
     (It logs a warning if it matched only the non-strict alternative)
     '''
     if strict is None:
         strict = getattr(tauruscustomsettings, 'STRICT_MODEL_NAMES', False)
     name = makeSchemeExplicit(name, default=self.scheme)
     m = self.name_re.match(name)
     # if it is strictly valid, return the groups
     if m is not None:
         ret = m.groupdict()
         ret['__STRICT__'] = True
         return ret
     # if we are strict (or no less-strict pattern is defined) return None
     if strict or self.nonStrictName_re is None:
         return None
     # If a less-strict pattern is defined, use it, but warn if it works
     m = self.nonStrictName_re.match(name)
     if m is None:
         return None
     else:
         from taurus import warning
         msg = ('Model name "%s" is supported but not strictly valid. \n' +
                'It is STRONGLY recommended that you change it to \n' +
                'strictly follow %s scheme syntax') % (name, self.scheme)
         warning(msg)
         ret = m.groupdict()
         ret['__STRICT__'] = False
         return ret
コード例 #10
0
ファイル: taurusvalidator.py プロジェクト: jkrueger1/taurus
 def _isValidAtLevel(self, name, matchLevel=None):
     # matchLevel is a tango-centric deprecated  argument of isValid. Warn.
     msg = ('matchLevel is a Tango-centric concept. Avoid it outside ' +
            'the tango scheme')
     from taurus import warning
     warning(msg)
     return self.isValid(name)
コード例 #11
0
ファイル: taurusvalidator.py プロジェクト: cmft/taurus
 def _isValidAtLevel(self, name, matchLevel=None):
     # matchLevel is a tango-centric deprecated  argument of isValid. Warn.
     msg = ('matchLevel is a Tango-centric concept. Avoid it outside ' +
            'the tango scheme')
     from taurus import warning
     warning(msg)
     return self.isValid(name)
コード例 #12
0
def fqdn_no_alias(hostname):
    """
    Normalize hostname so that it is a full name (including domain name).

    .. note:: this is similar to socket.getfqdn, but it avoids translating
              aliases into their "real" address.
    """
    if hostname == "localhost" or "." in hostname:
        # optimization: leave localhost or names including domain as they are
        return hostname
    try:
        real, aliases, _ = socket.gethostbyname_ex(hostname)
    except (socket.gaierror, socket.herror) as e:
        # return the given hostname in case of error
        return hostname

    if aliases:
        if hostname == real or hostname in aliases:
            # in some corner cases (e.g. when defining several aliases in a
            # hosts file), the hostname may be one of the aliases.
            return hostname

        # return alias if it exists
        if len(aliases) > 1:
            # warn in the (unusual) case that there is more than 1 alias
            warning("fqdn_no_alias: %s has %d aliases. Using the first one",
                    hostname, len(aliases))
        return aliases[0]
    else:
        # if there are no aliases, return real
        return real
コード例 #13
0
 def test_expert(self):
     CTRL_NAME = "unittestmotctrl01"
     MOT_NAME1 = "unittestmot01"
     MOT_NAME2 = "unittestmot02"
     try:
         self.macro_runs(macro_name="defctrl",
                         macro_params=["DummyMotorController", CTRL_NAME],
                         wait_timeout=1)
         self.macro_runs(macro_name="defelem",
                         macro_params=[MOT_NAME1, CTRL_NAME, "1"],
                         wait_timeout=1)
         self.macro_runs(macro_name="renameelem",
                         macro_params=[MOT_NAME1, MOT_NAME2],
                         wait_timeout=1)
         self.macro_runs(macro_name="defm",
                         macro_params=[MOT_NAME1, CTRL_NAME, "2"],
                         wait_timeout=1)
         self.macro_runs(macro_name="udefelem",
                         macro_params=[MOT_NAME1, MOT_NAME2],
                         wait_timeout=1)
         self.macro_runs(macro_name="udefctrl",
                         macro_params = [CTRL_NAME],
                         wait_timeout=1)
     except Exception, e:
         import taurus
         taurus.warning("Your system may stay dirty due to an unexpected"
                        " exception during the test.")
         raise e
コード例 #14
0
ファイル: taurusvalidator.py プロジェクト: cmft/taurus
 def getUriGroups(self, name, strict=None):
     '''returns the named groups dictionary from the URI regexp matching.
     If strict is False, it also tries to match against the non-strict regexp
     (It logs a warning if it matched only the non-strict alternative)
     '''
     if strict is None:
         strict = getattr(tauruscustomsettings, 'STRICT_MODEL_NAMES', False)
     name = makeSchemeExplicit(name, default=self.scheme)
     m = self.name_re.match(name)
     # if it is strictly valid, return the groups
     if m is not None:
         ret = m.groupdict()
         ret['__STRICT__'] = True
         return ret
     # if we are strict (or no less-strict pattern is defined) return None
     if strict or self.nonStrictName_re is None:
         return None
     # If a less-strict pattern is defined, use it, but warn if it works
     m = self.nonStrictName_re.match(name)
     if m is None:
         return None
     else:
         from taurus import warning
         msg = ('Model name "%s" is supported but not strictly valid. \n' +
                'It is STRONGLY recommended that you change it to \n' +
                'strictly follow %s scheme syntax') % (name, self.scheme)
         warning(msg)
         ret = m.groupdict()
         ret['__STRICT__'] = False
         return ret
コード例 #15
0
ファイル: taurusargparse.py プロジェクト: napppoli/taurus
def init_taurus_args(parser=None, args=None, values=None):
    """Parses the command line using :func:`taurus.core.util.argparse.parse_taurus_args`.

    After the command line is parsed, actions are taken on each recognized parameter.
    For example, the taurus log level and the default tango host are set accordingly.

    :param parser: an option parser or None (default) to create a new parser
    :type parser: :class:`optparse.OptionParser`
    :param args: the list of arguments to process (default is None meaning: sys.argv[1:])
    :type args: seq<str>
    :param values: a :class:`optparse.Values` object to store option arguments in
                  (default is None meaning: a new instance of Values) - if you give an
                  existing object, the option defaults will not be initialized on it
    :return: a tuple of three elements: parser, options, args
    :rtype: :class:`optparse.OptionParser`, :class:`optparse.Values`, seq<str> """
    import taurus
    parser, options, args = parse_taurus_args(parser=parser,
                                              args=args,
                                              values=values)

    # initialize taurus log level
    log_level_str = options.taurus_log_level.capitalize()
    if hasattr(taurus, log_level_str):
        log_level = getattr(taurus, log_level_str)
        taurus.setLogLevel(log_level)

    # initialize tango host
    if options.tango_host is not None:
        tango_factory = taurus.Factory("tango")
        tango_host = options.tango_host
        tango_factory.set_default_tango_host(tango_host)

    # initialize taurus polling period
    if options.taurus_polling_period is not None:
        taurus.Manager().changeDefaultPollingPeriod(
            options.taurus_polling_period)

    # initialize taurus serialization mode
    if options.taurus_serialization_mode is not None:
        import taurus.core.taurusbasetypes
        SerMode = taurus.core.taurusbasetypes.TaurusSerializationMode
        m = options.taurus_serialization_mode.capitalize()
        if hasattr(SerMode, m):
            m = getattr(SerMode, m)
            taurus.Manager().setSerializationMode(m)

    # initialize remote console port
    if options.remote_console_port is not None:
        try:
            import rfoo.utils.rconsole
            rfoo.utils.rconsole.spawn_server(port=options.remote_console_port)
            taurus.info(
                "rconsole started. You can connect to it by typing: rconsole -p %d",
                options.remote_console_port)
        except Exception, e:
            taurus.warning("Cannot spawn debugger. Reason: %s", str(e))
コード例 #16
0
def unit_from_tango(unit):
    if unit == PyTango.constants.UnitNotSpec:
        unit = None
    try:
        return UR.parse_units(unit)
    except UndefinedUnitError:
        # TODO: Maybe we could dynamically register the unit in the UR
        from taurus import warning
        warning('Unknown unit "%s (will be treated as dimensionless)"', unit)
        return UR.parse_units(None)
コード例 #17
0
ファイル: tango_taurus.py プロジェクト: srgblnch/taurus
def unit_from_tango(unit):
    if unit == PyTango.constants.UnitNotSpec:
        unit = None
    try:
        return UR.parse_units(unit)
    except UndefinedUnitError:
        # TODO: Maybe we could dynamically register the unit in the UR
        from taurus import warning
        warning('Unknown unit "%s (will be treated as dimensionless)"', unit)
        return UR.parse_units(None)
コード例 #18
0
ファイル: alt.py プロジェクト: dscran/taurus
def plot_cmd(models, config_file, x_axis_mode, demo, window_name, use_alt,
             ls_alt):
    """Shows a plot for the given models"""

    if ls_alt:
        _print_alts(EP_GROUP_PLOT)
        sys.exit(0)

    if use_alt is None:
        use_alt = getattr(_ts, "PLOT_ALT", ".*")

    try:
        TPlot, epname = _load_class_from_group(EP_GROUP_PLOT,
                                               include=[use_alt])
    except:
        _print_alts(EP_GROUP_PLOT)
        sys.exit(1)

    app = TaurusApplication(app_name="taurusplot({})".format(epname))

    w = TPlot()
    w.setWindowTitle(window_name)

    if demo:
        models = list(models)
        models.extend(["eval:rand(100)", "eval:0.5*sqrt(arange(100))"])

    try:
        w.setXAxisMode(x_axis_mode)
    except Exception as e:
        warning(
            'Could not set X axis mode to "%s" on %s plot. Reason: "%s"',
            x_axis_mode,
            epname,
            e,
        )
        sys.exit(1)

    if config_file is not None:
        try:
            w.loadConfigFile(config_file)
        except Exception as e:
            warning(
                'Could not load config file "%s" on %s plot. Reason: "%s"',
                config_file,
                epname,
                e,
            )
            sys.exit(1)

    if models:
        w.setModel(models)

    w.show()
    sys.exit(app.exec_())
コード例 #19
0
ファイル: taurusmodelchooser.py プロジェクト: dscran/taurus
 def __setTabItemModel(self):
     w = self.currentWidget()
     c = self.cursor()
     try:
         if not w.model:
             self.setCursor(QtCore.Qt.WaitCursor)
             w.setModel(w.default_model)
     except Exception as e:
         taurus.warning('Problem setting up selector: %r', e)
     finally:
         self.setCursor(c)
コード例 #20
0
ファイル: test_expert.py プロジェクト: reszelaz/sardana
 def test_meas(self):
     MNTGRP_NAME = "unittestmntgrp01"
     try:
         self.macro_runs(macro_name="defmeas",
                         macro_params=[MNTGRP_NAME, CT_NAME1, CT_NAME2])
         self.macro_runs(macro_name="udefmeas", macro_params=[MNTGRP_NAME])
     except Exception, e:
         import taurus
         taurus.warning("Your system may stay dirty due to an unexpected"
                        " exception during the test.")
         raise e
コード例 #21
0
 def __getattr__(self, member):
     try:
         mod = self.ep.load()
         # Replace lazy module with actual module for package
         setattr(sys.modules[self.__package__], self.__name__, mod)
         # Replace lazy module with actual module in sys.modules
         modname = "%s.%s" % (self.__package__, self.__name__)
         sys.modules[modname] = mod
     except Exception as e:
         warning('Could not load plugin "%s". Reason: %s', self.ep.name, e)
         return None
     return getattr(mod, member)
コード例 #22
0
ファイル: test_expert.py プロジェクト: cmft/sardana
 def test_meas(self):
     MNTGRP_NAME = "unittestmntgrp01"
     try:
         self.macro_runs(macro_name="defmeas",
                         macro_params=[MNTGRP_NAME, CT_NAME1, CT_NAME2])
         self.macro_runs(macro_name="udefmeas",
                         macro_params=[MNTGRP_NAME])
     except Exception, e:
         import taurus
         taurus.warning("Your system may stay dirty due to an unexpected"
                        " exception during the test.")
         raise e
コード例 #23
0
ファイル: taurusargparse.py プロジェクト: cmft/taurus
def init_taurus_args(parser=None, args=None, values=None):
    """Parses the command line using :func:`taurus.core.util.argparse.parse_taurus_args`.

    After the command line is parsed, actions are taken on each recognized parameter.
    For example, the taurus log level and the default tango host are set accordingly.

    :param parser: an option parser or None (default) to create a new parser
    :type parser: :class:`optparse.OptionParser`
    :param args: the list of arguments to process (default is None meaning: sys.argv[1:])
    :type args: seq<str>
    :param values: a :class:`optparse.Values` object to store option arguments in
                  (default is None meaning: a new instance of Values) - if you give an
                  existing object, the option defaults will not be initialized on it
    :return: a tuple of three elements: parser, options, args
    :rtype: :class:`optparse.OptionParser`, :class:`optparse.Values`, seq<str> """
    import taurus
    parser, options, args = parse_taurus_args(
        parser=parser, args=args, values=values)

    # initialize taurus log level
    log_level_str = options.taurus_log_level.capitalize()
    if hasattr(taurus, log_level_str):
        log_level = getattr(taurus, log_level_str)
        taurus.setLogLevel(log_level)

    # initialize tango host
    if options.tango_host is not None:
        tango_factory = taurus.Factory("tango")
        tango_factory.set_default_tango_host(options.tango_host)

    # initialize taurus polling period
    if options.taurus_polling_period is not None:
        taurus.Manager().changeDefaultPollingPeriod(options.taurus_polling_period)

    # initialize taurus serialization mode
    if options.taurus_serialization_mode is not None:
        import taurus.core.taurusbasetypes
        SerMode = taurus.core.taurusbasetypes.TaurusSerializationMode
        m = options.taurus_serialization_mode.capitalize()
        if hasattr(SerMode, m):
            m = getattr(SerMode, m)
            taurus.Manager().setSerializationMode(m)

    # initialize remote console port
    if options.remote_console_port is not None:
        try:
            import rfoo.utils.rconsole
            rfoo.utils.rconsole.spawn_server(port=options.remote_console_port)
            taurus.info("rconsole started. You can connect to it by typing: rconsole -p %d",
                        options.remote_console_port)
        except Exception, e:
            taurus.warning("Cannot spawn debugger. Reason: %s", str(e))
コード例 #24
0
def unit_from_tango(unit):
    from taurus import deprecated
    deprecated(dep='unit_from_tango', rel='4.0.4', alt="pint's parse_units")

    if unit == PyTango.constants.UnitNotSpec:
        unit = None
    try:
        return UR.parse_units(unit)
    except (UndefinedUnitError, UnicodeDecodeError):
        # TODO: Maybe we could dynamically register the unit in the UR
        from taurus import warning
        warning('Unknown unit "%s (will be treated as unitless)"', unit)
        return UR.parse_units(None)
コード例 #25
0
ファイル: taurusvalidator.py プロジェクト: jkrueger1/taurus
 def getParams(self, name):
     # deprecation warning
     msg = ('%s.getParams() is deprecated. Use getUriGroups() instead.' %
            self.__class__.__name__)
     from taurus import warning
     warning(msg)
     # support old group names
     groups = self.getUriGroups(name, strict=False)
     if groups is None:
         return None
     groups = dict(groups)  # copy, just in case
     groups['devicename'] = groups.get('devname')
     groups['devalias'] = groups.get('_devalias')
     groups['attributename'] = groups.get('_shortattrname')
     groups['configparam'] = groups.get('fragment')
     return groups
コード例 #26
0
ファイル: taurusvalidator.py プロジェクト: cmft/taurus
 def getParams(self, name):
     # deprecation warning
     msg = ('%s.getParams() is deprecated. Use getUriGroups() instead.' %
            self.__class__.__name__)
     from taurus import warning
     warning(msg)
     # support old group names
     groups = self.getUriGroups(name, strict=False)
     if groups is None:
         return None
     groups = dict(groups)  # copy, just in case
     groups['devicename'] = groups.get('devname')
     groups['devalias'] = groups.get('_devalias')
     groups['attributename'] = groups.get('_shortattrname')
     groups['configparam'] = groups.get('fragment')
     return groups
コード例 #27
0
 def run(self):
     try:
         import tango
     except ImportError:
         Worker.run(self)
     # Tango is not thread safe when using threading.Thread. One must
     # use omni threads instead. This was confirmed for parallel
     # event subscriptions in PyTango#307. Use EnsureOmniThread introduced
     # in PyTango#327 whenever available.
     else:
         if hasattr(tango, "EnsureOmniThread"):
             with tango.EnsureOmniThread():
                 Worker.run(self)
         else:
             import taurus
             taurus.warning("Your Sardana system is affected by bug "
                            "tango-controls/pytango#307. Please use "
                            "PyTango with tango-controls/pytango#327.")
             Worker.run(self)
コード例 #28
0
ファイル: taurusmodelchooser.py プロジェクト: dscran/taurus
    def __init__(self, parent=None):
        Qt.QTabWidget.__init__(self, parent=parent)

        self.currentChanged.connect(self.__setTabItemModel)
        # ---------------------------------------------------------------------
        # Note: this is an experimental feature
        # It may be removed or changed in future releases
        # Discover the taurus.modelselector plugins
        ep_group_name = 'taurus.model_selector.items'
        for ep in pkg_resources.iter_entry_points(ep_group_name):
            try:
                ms_class = ep.load()
                ms_item = ms_class(parent=self)
                self.__addItem(ms_item, ep.name)

            except Exception as e:
                err = 'Invalid TaurusModelSelectorItem plugin: {}\n{}'.format(
                    ep.module_name, e)
                taurus.warning(err)
コード例 #29
0
ファイル: sardemoenv.py プロジェクト: rhomspuron/sardana
def getElements(elem_type="all", fallback_name="element_not_defined",
                fallback_elements_len=5):
    if fallback_name is None:
        fallback_name = elem_type + "_not_defined"
    try:
        elements = SarDemoEnv().getElements(elem_type)
    except RuntimeError:
        import taurus
        from sardana import sardanacustomsettings
        door_name = getattr(sardanacustomsettings, 'UNITTEST_DOOR_NAME',
                            'UNDEFINED')
        taurus.warning("The door %s is not running. " % (door_name) +
                       "Ignore this message if you are building the documentation.")
        elements = [fallback_name] * fallback_elements_len
    except Exception, e:
        import taurus
        taurus.debug(e)
        taurus.warning("It was not possible to retrieve the element. " +
                       "Ignore this message if you are building the documentation.")
        elements = [fallback_name] * fallback_elements_len
コード例 #30
0
ファイル: sardemoenv.py プロジェクト: quanpower/sardana
def getElements(elem_type="all",
                fallback_name="element_not_defined",
                fallback_elements_len=5):
    if fallback_name is None:
        fallback_name = elem_type + "_not_defined"
    try:
        elements = SarDemoEnv().getElements(elem_type)
    except RuntimeError:
        import taurus
        from sardana import sardanacustomsettings
        door_name = getattr(sardanacustomsettings, 'UNITTEST_DOOR_NAME',
                            'UNDEFINED')
        taurus.warning(
            "The door %s is not running. " % (door_name) +
            "Ignore this message if you are building the documentation.")
        elements = [fallback_name] * fallback_elements_len
    except Exception, e:
        import taurus
        taurus.debug(e)
        taurus.warning(
            "It was not possible to retrieve the element. " +
            "Ignore this message if you are building the documentation.")
        elements = [fallback_name] * fallback_elements_len
コード例 #31
0
def get_thread_pool():
    """Returns the global pool of threads for Sardana

    :return: the global pool of threads object
    :rtype: taurus.core.util.ThreadPool"""

    global __thread_pool
    global __thread_pool_lock
    with __thread_pool_lock:
        if __thread_pool is None:
            # protect older versions of Taurus (without the worker_cls
            # argument) remove it whenever we bump Taurus dependency
            try:
                __thread_pool = ThreadPool(name="SardanaTP",
                                           Psize=10,
                                           worker_cls=OmniWorker)
            except TypeError:
                import taurus
                taurus.warning("Your Sardana system is affected by bug "
                               "tango-controls/pytango#307. Please use "
                               "Taurus with taurus-org/taurus#1081.")
                __thread_pool = ThreadPool(name="SardanaTP", Psize=10)

        return __thread_pool
コード例 #32
0
    def __init__(self, host=None, port=None, parent=None):
        if host is None or port is None:
            try:
                _hp = TangoAuthority.get_default_tango_host()
                host, port = _hp.rsplit(':', 1)
            except Exception:
                from taurus import warning
                warning("Error getting default Tango host")

        # Set host to fqdn
        host = socket.getfqdn(host)

        self.dbObj = Database(host, port)
        self._dbProxy = None
        self._dbCache = None

        complete_name = "tango://%s:%s" % (host, port)
        self.call__init__(TaurusAuthority, complete_name, parent)

        try:
            self.get_class_for_device(self.dev_name())
        except:
            # Ok, old tango database.
            self.get_class_for_device = self.__get_class_for_device
コード例 #33
0
    def tickValues(self, minVal, maxVal, size):
        """
        Reimplemented from PlotItem to adjust to the range and to force
        the ticks at "round" positions in the context of time units instead of
        rounding in a decimal base
        """

        maxMajSteps = int(size // self._pxLabelWidth)

        dx = maxVal - minVal
        majticks = []

        try:
            dt1 = datetime.fromtimestamp(minVal)
            dt2 = datetime.fromtimestamp(maxVal)
        except Exception as e:
            from taurus import warning

            warning("Invalid range in DateTime axis: %s", e)
            return [(dx, [])]

        if dx > 63072001:  # 3600s*24*(365+366) = 2 years (count leap year)
            d = timedelta(days=366)
            for y in range(dt1.year + 1, dt2.year + 1):
                dt = datetime(year=y, month=1, day=1)
                majticks.append(mktime(dt.timetuple()))

        elif dx > 5270400:  # 3600s*24*61 = 61 days
            d = timedelta(days=31)
            dt = (
                dt1.replace(day=1, hour=0, minute=0, second=0, microsecond=0) +
                d)
            while dt < dt2:
                # make sure that we are on day 1 (even if always sum 31 days)
                dt = dt.replace(day=1)
                majticks.append(mktime(dt.timetuple()))
                dt += d

        elif dx > 172800:  # 3600s24*2 = 2 days
            d = timedelta(days=1)
            dt = dt1.replace(hour=0, minute=0, second=0, microsecond=0) + d
            while dt < dt2:
                majticks.append(mktime(dt.timetuple()))
                dt += d

        elif dx > 7200:  # 3600s*2 = 2hours
            d = timedelta(hours=1)
            dt = dt1.replace(minute=0, second=0, microsecond=0) + d
            while dt < dt2:
                majticks.append(mktime(dt.timetuple()))
                dt += d

        elif dx > 1200:  # 60s*20 = 20 minutes
            d = timedelta(minutes=10)
            dt = (dt1.replace(
                minute=(dt1.minute // 10) * 10, second=0, microsecond=0) + d)
            while dt < dt2:
                majticks.append(mktime(dt.timetuple()))
                dt += d

        elif dx > 120:  # 60s*2 = 2 minutes
            d = timedelta(minutes=1)
            dt = dt1.replace(second=0, microsecond=0) + d
            while dt < dt2:
                majticks.append(mktime(dt.timetuple()))
                dt += d

        elif dx > 20:  # 20s
            d = timedelta(seconds=10)
            dt = dt1.replace(second=(dt1.second // 10) * 10, microsecond=0) + d
            while dt < dt2:
                majticks.append(mktime(dt.timetuple()))
                dt += d

        elif dx > 2:  # 2s
            d = timedelta(seconds=1)
            # majticks = list(range(int(minVal), int(maxVal)))
            majticks = list(
                range(int(numpy.ceil(minVal)), int(numpy.ceil(maxVal))))

        else:  # <2s , use standard implementation from parent
            return AxisItem.tickValues(self, minVal, maxVal, size)

        # print("majticks >: ", majticks)

        L = len(majticks)
        if L > maxMajSteps:
            if maxMajSteps == 0:
                majticks = []
            else:
                majticks = majticks[::int(numpy.ceil(float(L) / maxMajSteps))]

        # print("majticks <: ", majticks)
        # print "----------------------------"

        return [(d.total_seconds(), majticks)]
コード例 #34
0
ファイル: util.py プロジェクト: victorfong28/sardana
def prepare_logging(options,
                    args,
                    tango_args,
                    start_time=None,
                    log_messages=None):
    taurus.setLogLevel(taurus.Debug)
    root = Logger.getRootLog()

    # output logger configuration
    log_output_level = options.log_level
    log_level_map = {
        "0": taurus.Critical,
        "critical": taurus.Critical,
        "1": taurus.Error,
        "error": taurus.Error,
        "2": taurus.Warning,
        "warning": taurus.Warning,
        "3": taurus.Info,
        "info": taurus.Info,
        "4": taurus.Debug,
        "debug": taurus.Debug,
        "5": taurus.Trace,
        "trace": taurus.Trace,
    }
    log_output_level = log_level_map[log_output_level]
    root.handlers[0].setLevel(log_output_level)

    if not options.without_log_file:
        log_file_level = options.log_file_level
        log_file_level = log_level_map[log_file_level]

        # Create a file handler
        if options.log_file_name is None:
            _, ds_name = os.path.split(args[0])
            ds_name, _ = os.path.splitext(ds_name)
            ds_instance = args[-1].lower()
            import getpass
            try:
                # include the user name to avoid permission errors
                tangodir = 'tango-%s' % getpass.getuser()
            except:
                tangodir = 'tango' % getpass.getuser()
            path = os.path.join(os.sep, "tmp", tangodir, ds_name, ds_instance)
            log_file_name = os.path.join(path, 'log.txt')
        else:
            log_file_name = options.log_file_name
        path = os.path.dirname(log_file_name)

        # because some versions of python have a bug in logging.shutdown (this
        # function is not protected against deleted handlers) we store the
        # handlers we create to make sure a strong reference exists when the
        # logging.shutdown is called
        taurus._handlers = handlers = []
        try:
            if not os.path.exists(path):
                os.makedirs(path, 0777)

            from sardana import sardanacustomsettings
            maxBytes = getattr(sardanacustomsettings, 'LOG_FILES_SIZE', 1E7)
            backupCount = getattr(sardanacustomsettings, 'LOG_BCK_COUNT', 5)

            fmt = Logger.getLogFormat()
            f_h = logging.handlers.RotatingFileHandler(log_file_name,
                                                       maxBytes=maxBytes,
                                                       backupCount=backupCount)
            f_h.setFormatter(fmt)
            f_h.setLevel(log_file_level)
            root.addHandler(f_h)
            handlers.append(f_h)

            if start_time is not None:
                taurus.info("Started at %s", start_time)
            else:
                taurus.info("Starting up...")
            taurus.info("Log is being stored in %s", log_file_name)
        except:
            if start_time is not None:
                taurus.info("Started at %s", start_time)
            else:
                taurus.info("Starting up...")
            taurus.warning(
                "'%s' could not be created. Logs will not be stored",
                log_file_name)
            taurus.debug("Error description", exc_info=1)

    if log_messages is None:
        log_messages = []
    for log_message in log_messages:
        taurus.info(*log_message)

    taurus.debug("Start args=%s", args)
    taurus.debug("Start tango args=%s", tango_args)
    taurus.debug("Start options=%s", options)
    taurus.debug("Using PyTango %s from %s", PyTango.Release.version,
                 PyTango.__path__[0])
    taurus.debug("Using taurus %s from %s", taurus.Release.version,
                 taurus.__path__[0])
    taurus.debug("Using sardana %s from %s", sardana.Release.version,
                 sardana.__path__[0])
コード例 #35
0
ファイル: test_epicsattribute.py プロジェクト: cmft/taurus
 def tearDownClass(cls):
     """Terminate the epics_test softIoc process"""
     if cls._process:
         cls._process.terminate()
     else:
         taurus.warning('Process not started, cannot terminate it.')
コード例 #36
0
ファイル: util.py プロジェクト: cmft/sardana
def prepare_logging(options, args, tango_args, start_time=None, log_messages=None):
    taurus.setLogLevel(taurus.Debug)
    root = Logger.getRootLog()

    # output logger configuration
    log_output_level = options.log_level
    log_level_map = { "0" : taurus.Critical, "critical" : taurus.Critical,
                       "1" : taurus.Error, "error" : taurus.Error,
                       "2" : taurus.Warning, "warning" : taurus.Warning,
                       "3" : taurus.Info, "info" : taurus.Info,
                       "4" : taurus.Debug, "debug" : taurus.Debug,
                       "5" : taurus.Trace, "trace" : taurus.Trace,
                     }
    log_output_level = log_level_map[log_output_level]
    root.handlers[0].setLevel(log_output_level)

    if not options.without_log_file:
        log_file_level = options.log_file_level
        log_file_level = log_level_map[log_file_level]

        # Create a file handler
        if options.log_file_name is None:
            _, ds_name = os.path.split(args[0])
            ds_name, _ = os.path.splitext(ds_name)
            ds_instance = args[-1].lower()
            import getpass
            try:
                tangodir = 'tango-%s' % getpass.getuser()  #include the user name to avoid permission errors
            except:
                tangodir = 'tango' % getpass.getuser()
            path = os.path.join(os.sep, "tmp", tangodir, ds_name, ds_instance)
            log_file_name = os.path.join(path, 'log.txt')
        else:
            log_file_name = options.log_file_name
        path = os.path.dirname(log_file_name)

        # because some versions of python have a bug in logging.shutdown (this
        # function is not protected against deleted handlers) we store the
        # handlers we create to make sure a strong reference exists when the
        # logging.shutdown is called
        taurus._handlers = handlers = []
        try:
            if not os.path.exists(path):
                os.makedirs(path, 0777)
            
            from sardana import sardanacustomsettings    
            maxBytes = getattr(sardanacustomsettings, 'LOG_FILES_SIZE', 1E7)
            backupCount = getattr(sardanacustomsettings, 'LOG_BCK_COUNT', 5)

            fmt = Logger.getLogFormat()
            f_h = logging.handlers.RotatingFileHandler(log_file_name,
                                                       maxBytes=maxBytes,
                                                       backupCount=backupCount)
            f_h.setFormatter(fmt)
            f_h.setLevel(log_file_level)
            root.addHandler(f_h)
            handlers.append(f_h)

            if start_time is not None:
                taurus.info("Started at %s", start_time)
            else:
                taurus.info("Starting up...")
            taurus.info("Log is being stored in %s", log_file_name)
        except:
            if start_time is not None:
                taurus.info("Started at %s", start_time)
            else:
                taurus.info("Starting up...")
            taurus.warning("'%s' could not be created. Logs will not be stored",
                           log_file_name)
            taurus.debug("Error description", exc_info=1)

    if log_messages is None:
        log_messages = []
    for log_message in log_messages:
        taurus.info(*log_message)

    taurus.debug("Start args=%s", args)
    taurus.debug("Start tango args=%s", tango_args)
    taurus.debug("Start options=%s", options)
    taurus.debug("Using PyTango %s from %s", PyTango.Release.version, PyTango.__path__[0])
    taurus.debug("Using taurus %s from %s", taurus.Release.version, taurus.__path__[0])
    taurus.debug("Using sardana %s from %s", sardana.Release.version, sardana.__path__[0])
コード例 #37
0
def set_properties_on_curves(properties, curves, plotItem=None, y2Axis=None):
    """
    Sets properties provided in the `properties` dict to curves provided in
    the `curves` dict. The association of a given curve with a property is
    done by matching the keys in the respective dictionaries.
    If both `plotItem` and `y2Axis` are passed, the curve will be moved to the
    ViewBox defined in the .y2 property
    :param properties: dict whose values are :class:`CurveAppearanceProperties`
                       instances and whose keys arbitrarily identify a
                       given curve
    :param curves: dict whose values are :class:`PlotDataItem` instances
                   and whose keys match those of properties (if a key in
                   `curves` does not exist in `properties`, it will be ignored)
    :param plotItem: The :class:`PlotItem` containing the dataItem.
    :param y2Axis: The :class:`Y2ViewBox` instance
 e skipp   """

    for key, dataItem in curves.items():
        try:
            prop = properties[key]
        except KeyError:
            warning("Cannot restore curve '%s' (no known properties)", key)
            continue
        sStyle = prop.sStyle
        sSize = prop.sSize
        sColor = prop.sColor
        sFill = prop.sFill
        lStyle = prop.lStyle
        lWidth = prop.lWidth
        lColor = prop.lColor
        cFill = prop.cFill
        stepMode = prop.stepMode
        y2 = prop.y2
        title = prop.title

        dataItem.setPen(dict(style=lStyle, width=lWidth, color=lColor))
        if cFill is not None:
            dataItem.setFillLevel(cFill)
            try:
                cFillColor = Qt.QColor(lColor)
                cFillColor.setAlphaF(0.5)  # set to semitransparent
            except Exception:
                cFillColor = lColor
            dataItem.setFillBrush(cFillColor)
        else:
            dataItem.setFillLevel(None)

        dataItem.setSymbol(sStyle)
        # dataItem.setSymbolPen(pyqtgraph.mkPen(color=sColor))
        if sStyle is None or sSize < 0:
            dataItem.setSymbolSize(0)
        else:
            dataItem.setSymbolSize(sSize)

        if sFill:
            dataItem.setSymbolBrush(pyqtgraph.mkColor(sColor))
        else:
            dataItem.setSymbolBrush(None)

        dataItem.opts["stepMode"] = stepMode
        dataItem.updateItems()

        if title is not None:
            # set the title of the curve
            dataItem.setData(name=title)
            # update the corresponding label in the legend
            if plotItem is not None and plotItem.legend is not None:
                if hasattr(plotItem.legend, "getLabel"):
                    plotItem.legend.getLabel(dataItem).setText(title)
                else:
                    # workaround for pyqtgraph<=0.11 (getLabel not implemented)
                    for sample, label in plotItem.legend.items:
                        if sample.item == dataItem:
                            label.setText(title)
                            break

        # act on the ViewBoxes only if plotItem and y2Axis are given
        if plotItem and y2Axis:
            set_y_axis_for_curve(y2, dataItem, plotItem, y2Axis)
コード例 #38
0
    def updateModels(self, xy_names):
        """
        Update the current plot item list with the given configuration items
        """
        mainViewBox = self.plot_item.getViewBox()
        # Remove existing taurus curves from the plot (but keep the item object
        # and a reference to their viewbox so that they can be readded
        # later on if needed.
        currentModelItems = OrderedDict()
        _currentCurves = list(self.plot_item.listDataItems())
        for curve in _currentCurves:
            if isinstance(curve, self.itemClass):
                xname, yname = curve.getFullModelNames()
                viewbox = curve.getViewBox()
                # store curve and current viewbox for later use
                currentModelItems[(xname, yname)] = curve, viewbox
                # remove the curve
                self.plot_item.removeItem(curve)
                # if viewbox is not mainViewBox:  # TODO: do we need this?
                #     viewbox.removeItem(curve)
                if self.legend is not None:
                    self.legend.removeItem(curve.name())

        # Add only the curves defined in xy_names (reusing existing ones and
        # creating those that did not exist) in the desired z-order
        _already_added = []
        for xy_name in xy_names:
            # each member of xy_names can be yname or a (xname, yname) tuple
            if isinstance(xy_name, string_types):
                xname, yname = None, xy_name
            else:
                xname, yname = xy_name
            # make sure that fullnames are used
            try:
                if xname is not None:
                    xmodel = taurus.Attribute(xname)
                    xname = xmodel.getFullName()
                ymodel = taurus.Attribute(yname)
                yname = ymodel.getFullName()
            except Exception as e:
                from taurus import warning

                warning("Problem adding %r: %r", (xname, yname), e)
                continue
            # do not add it again if we already added it (avoid duplications)
            if (xname, yname) in _already_added:
                continue
            _already_added.append((xname, yname))
            # if the item already existed, re-use it
            if (xname, yname) in currentModelItems:
                item, viewbox = currentModelItems[(xname, yname)]
                self.plot_item.addItem(item)
                if viewbox is not mainViewBox:
                    # if the curve was originally associated to a viewbox
                    # other than the main one, we should move it there after
                    # re-adding it to the plot_item
                    mainViewBox.removeItem(item)
                    viewbox.addItem(item)
            # if it is a new curve, create it and add it to the main plot_item
            else:
                item = self.itemClass(xModel=xname,
                                      yModel=yname,
                                      name=ymodel.getSimpleName())
                if self._curveColors is not None:
                    item.setPen(self._curveColors.next().color())
                self.plot_item.addItem(item)
コード例 #39
0
    def _onTriggered(self):
        currentModelItems = {}
        currentModelNames = []
        taurusItems = []

        for curve in self.plot_item.listDataItems():
            if isinstance(curve, TaurusPlotDataItem):
                xmodel, ymodel = curve.getFullModelNames()
                currentModelNames.append((xmodel, ymodel))
                currentModelItems[(xmodel, ymodel)] = curve, curve.getViewBox()
                taurusItems.append(TaurusItemConf(YModel=ymodel, XModel=xmodel,
                                                  name=curve.name()))

        conf, ok = TaurusItemConfDlg.showDlg(
            parent=self.parent(), taurusItemConf=taurusItems)

        # print conf, ok

        if ok:
            yModels = OrderedDict()
            xModels = OrderedDict()
            curve_name = OrderedDict()
            for c in conf:
                try:
                    # print c.yModel, type(c.yModel)
                    m = taurus.Attribute(c.yModel)
                    n = c.xModel
                    name = c.curveLabel
                    yModels[n, m.getFullName()] = m
                    xModels[n, m.getFullName()] = n
                    curve_name[n, m.getFullName()] = name
                except Exception as e:
                    from taurus import warning
                    warning(e)

            for k, v in currentModelItems.items():
                curve, parent = v
                self.plot_item.removeItem(curve)
                parent.removeItem(curve)
                if self.legend is not None:
                    self.legend.removeItem(curve.name())

            for modelName, model in yModels.items():
                # print modelName, model
                if modelName in currentModelNames:
                    item, parent = currentModelItems[modelName]
                    X = xModels[modelName]
                    c_name = curve_name[modelName]
                    item.opts['name'] = c_name
                    item.setXModel(X)
                    self.plot_item.addItem(item)

                    # checks if the viewBox associated to
                    # TaurusPlotDataItem(curve), it is the main view or not.
                    # If is the same, we dont have to addItem again in the
                    # parent (viewBox). This avoid duplicate objects in the
                    # ViewBox.scene() contained in PlotItem.
                    if parent is not self.plot_item.getViewBox():
                        parent.addItem(item)

                elif modelName not in currentModelNames:
                    x_model = xModels[modelName]
                    y_model = yModels[modelName]
                    c_name = curve_name[modelName]
                    item = TaurusPlotDataItem(
                        xModel=x_model, yModel=y_model, name=c_name)

                    if self._curveColors is not None:
                        item.setPen(self._curveColors.next().color())
                    self.plot_item.addItem(item)
コード例 #40
0
ファイル: test_epicsattribute.py プロジェクト: tcsgmrt/taurus
 def tearDownClass(cls):
     """Terminate the epics_test softIoc process"""
     if cls._process:
         cls._process.terminate()
     else:
         taurus.warning('Process not started, cannot terminate it.')
コード例 #41
0
ファイル: taurusvalidator.py プロジェクト: cmft/taurus
 def __init__(self, *args, **kwargs):
     msg = ('%s is deprecated. Use "Authority" instead of "Database"' %
            self.__class__.__name__)
     from taurus import warning
     warning(msg)
     return TaurusAuthorityNameValidator.__init__(self, *args, **kwargs)
コード例 #42
0
ファイル: taurusform.py プロジェクト: dscran/taurus
    def fillWithChildren(self):
        frame = TaurusWidget()
        frame.setLayout(Qt.QGridLayout())
        frame.layout().addItem(
            Qt.QSpacerItem(0, 0, Qt.QSizePolicy.Minimum,
                           Qt.QSizePolicy.MinimumExpanding))

        parent_name = None
        if self.getUseParentModel():
            parent_model = self.getParentModelObj()
            if parent_model:
                parent_name = parent_model.getFullName()

        for i, model in enumerate(self.getModel()):
            if not model:
                continue
            try:
                model_obj = taurus.Object(model)
            except:
                self.warning('problem adding item "%s"', model)
                self.traceback(level=taurus.Debug)
                continue
            if parent_name:
                # @todo: Change this (it assumes tango model naming!)
                model = "%s/%s" % (parent_name, model)

            widget = None
            # check if some item factory handles this model
            for ep in self._itemFactories:
                try:
                    # load the plugin
                    f = ep.load()
                except:
                    warning('cannot load item factory "%s"', ep.name)
                    continue
                try:
                    widget = f(model_obj)
                except Exception as e:
                    warning(
                        'factory "%s" raised "%r" for "%s". ' +
                        'Tip: consider disabling it', ep.name, e, model)
                if widget is not None:
                    self.debug("widget for '%s' provided by '%s'", model,
                               ep.name)
                    break

            # backwards-compat with deprecated custom widget map API
            if widget is None and self._customWidgetMap:
                widget = self._customWidgetFactory(model_obj)

            # no factory handles the model and no custom widgets. Use default
            if widget is None:
                widget = self._defaultFormWidget()

            # @todo UGLY... See if this can be done in other ways... (this causes trouble with widget that need more vertical space , like PoolMotorTV)
            widget.setMinimumHeight(20)

            try:
                widget.setCompact(self.isCompact())
                widget.setModel(model)
                widget.setParent(frame)
            except:
                # raise
                self.warning('problem adding item "%s"', model)
                self.traceback(level=taurus.Debug)
            try:
                widget.setModifiableByUser(self.isModifiableByUser())
            except:
                pass
            try:
                widget.setFormat(self.getFormat())
            except Exception:
                self.debug('Cannot set format %s to child %s',
                           self.getFormat(), model)
            widget.setObjectName("__item%i" % i)
            self.registerConfigDelegate(widget)
            self._children.append(widget)

        frame.layout().addItem(
            Qt.QSpacerItem(0, 0, Qt.QSizePolicy.Minimum,
                           Qt.QSizePolicy.MinimumExpanding))
        self.scrollArea.setWidget(frame)
        #        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setMinimumWidth(frame.layout().sizeHint().width() + 20)
コード例 #43
0
ファイル: taurusvalidator.py プロジェクト: jkrueger1/taurus
 def __init__(self, *args, **kwargs):
     msg = ('%s is deprecated. Use "Authority" instead of "Database"' %
            self.__class__.__name__)
     from taurus import warning
     warning(msg)
     return TaurusAuthorityNameValidator.__init__(self, *args, **kwargs)