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()
def main(): import taurus taurus.setLogLevel(taurus.Warning) tg_host = None if len(sys.argv) > 1: tg_host = sys.argv[1] t1(tg_host=tg_host)
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)
def start(user_ns=None): # Make sure the log level is changed to warning CodecFactory() taurus.setLogLevel(taurus.Warning) try: check_requirements() except exception.SpockMissingRequirement as requirement: print(str(requirement)) sys.exit(-1) except exception.SpockMissingRecommended as recommended: print(str(recommended)) user_ns = user_ns or {} try: user_ns.update(get_args(sys.argv)) except exception.SpockException as e: print(e) print('Starting normal IPython console') except KeyboardInterrupt: print("\nUser pressed Ctrl+C. Exiting...") sys.exit() except Exception as e: print('spock exited with an unmanaged exception: %s' % str(e)) sys.exit(-2) app = TerminalIPythonApp.instance() app.initialize() #config = get_config() return app
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()
def jdraw_view_main(): import sys import time import taurus.qt.qtgui.graphic taurus.setLogLevel(taurus.Info) from taurus.qt.qtgui.application import TaurusApplication app = TaurusApplication(sys.argv) #form = Qt.QDialog() # ly=Qt.QVBoxLayout(form) # container=Qt.QWidget() # ly.addWidget(container) # for m in sys.argv[1:]: #tv=TaurusJDrawSynopticsView(container, designMode=False) # tv.setModel(m) form = taurus.qt.qtgui.graphic.TaurusJDrawSynopticsView(designMode=False) form.show() # print '%s setModel(%s)'%(time.ctime(),sys.argv[1]) form.setModel(sys.argv[1]) form.setWindowTitle(sys.argv[1].rsplit('.', 1)[0]) #def kk(*args):print("\tgraphicItemSelected(%s)"%str(args)) #form.connect(form,Qt.SIGNAL("graphicItemSelected(QString)"), kk) # form.fitting() sys.exit(app.exec_())
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))
def start(user_ns=None): # Make sure the log level is changed to warning CodecFactory() taurus.setLogLevel(taurus.Warning) try: check_requirements() except exception.SpockMissingRequirement, requirement: print str(requirement) sys.exit(-1)
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))
def prepareToLog(app, appName): LOGDIR = "/control/logs" ALTERNATIVE_LOGDIR = "/tmp" if os.path.isdir(LOGDIR): logdirectory = LOGDIR else: logdirectory = ALTERNATIVE_LOGDIR hostname = gethostname() username = getuser() logfilename = "%s/%s_%s_%s.log" % (logdirectory, appName, hostname, username) app.basicConfig(log_file_name=logfilename) setLogLevel(Info)
def main(): """Register subcommands and run taurus_cmd""" # 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) # register the subcommands register_subcommands() # launch the taurus command taurus_cmd()
def setUp(self): taurus.setLogLevel(taurus.Critical) self.opt_mods = ("QtDesigner", "QtNetwork", "Qt", "QtSvg", "QtUiTools", "QtWebKit", "Qwt5", "uic") # store a "snapshot" of the currently loaded modules self._orig_mods = set(sys.modules.keys()) # this import initializes Qt in case it is not loaded from taurus.external.qt import Qt, API_NAME self._api_name = API_NAME self.__qt = Qt
def test(model, filters='', debug=False): if debug: taurus.setLogLevel(taurus.core.util.Logger.Debug) form.setWindowTitle(model) print 'loading synoptic: %s' % model form = VaccaSynoptic(delay=1000, designMode=False) #form = taurus.qt.qtgui.graphic.TaurusJDrawSynopticsView(designMode=False) #designMode=False,updateMode=VaccaSynoptic.NoViewportUpdate) form.show() form.setModel(model) form.setWindowTitle(model) print 'showing ...' return form
def main(args): import sys, re, traceback, taurus assert len( args ) > 1, '\n\nUsage:\n\t> python panel.py [a/device/name or synoptic.jdw] [--attrs] [attr_regexps] --comms [comm_regexps]' model = args[1] taurus.setLogLevel(taurus.core.util.Logger.Debug) app = Qt.QApplication(args) form = None if re.match('[\w-]+/[\w-]+/[\w-]+.*', model): print 'loading a device panel' k, filters = '--attrs', fandango.defaultdict(list) for f in args[2:]: if f.startswith('--'): k = f.strip('-') else: filters[k].append(f) #(f,()) if k=='comms' else f) form = VaccaPanel(filters=filters) #palette=get_fullWhite_palette() form.setModel(model) elif model.lower().endswith('.jdw'): print 'loading a synoptic' form = taurus.qt.qtgui.graphic.TauJDrawSynopticsView( designMode=False, updateMode=taurus.qt.qtgui.graphic.TauJDrawSynopticsView. NoViewportUpdate) #FullViewportUpdate, : AWFUL CPU USAGE!!!!!!!! #MinimalViewportUpdate, : Qt Defaults #SmartViewportUpdate, : ? #BoundingRectViewportUpdate, : ? #NoViewportUpdate : Tau defaults form.setModel(model) models = form.get_item_list() for m in models: m = str(m) if m.count('/') == 2: m += '/state' period = 120000. try: taurus.Attribute(m).changePollingPeriod(period) except: print '(%s).changePollingPeriod(%s): Failed: %s' % ( m, period, traceback.format_exc()) print 'showing ...' form.show() sys.exit(app.exec_())
def setModel(self, model, alias=None, delayed=False, trace=False): self.modelName = str(model) self._currF = str(model) if alias is not None: self.setAlias(alias) ll = taurus.getLogLevel() if trace: taurus.setLogLevel(taurus.Debug) # self.debug('setModel("%s")'%model) if self._currF: #filename = str(self._currFile.absoluteFilePath()) filename = self._currF filename = os.path.realpath(filename) if os.path.isfile(filename): self.debug("Starting to parse %s" % filename) self.path = os.path.dirname(filename) factory = self.getGraphicsFactory(delayed=delayed) scene = parse(filename, factory) scene.setSelectionStyle(self._selectionStyle) self.debug("Obtained %s(%s)", type(scene).__name__, filename) if not scene: self.warning( "TaurusJDrawSynopticsView.setModel(%s): Unable to parse %s!!!" % (model, filename)) elif self.w_scene is None and scene.sceneRect(): self.w_scene = scene.sceneRect().width() self.h_scene = scene.sceneRect().height() else: self.debug('JDrawView.sceneRect() is NONE!!!') self.setScene(scene) self.scene().graphicItemSelected.connect( self._graphicItemSelected) self.scene().graphicSceneClicked.connect( self._graphicSceneClicked) # Qt.QApplication.instance().lastWindowClosed.connect(self.close) #It caused a # segfault! self.__modelsChanged() self.setWindowTitle(self.modelName) # The emitted signal contains the filename and a dictionary # with the name of items and its color self.emitColors() # get_item_colors(emit=True) self.fitting() else: self.setScene(None) #self.debug('out of setModel()') taurus.setLogLevel(ll)
def main(group, taurus_log_level, door): import taurus taurus.setLogLevel(getattr(taurus, taurus_log_level.capitalize())) from taurus.qt.qtgui.application import TaurusApplication app = TaurusApplication(app_name='Showscan Online', org_domain="Sardana", org_name="Tango communinity", cmd_line_parser=None) assertPlotAvailability() widget = ScanWindow() widget.plot_widget.setGroupMode(group) widget.setModel(door) widget.show() return app.exec_()
def setModel(self, model, alias=None, delayed=False, trace=False): self.modelName = str(model) self._currF = str(model) if alias is not None: self.setAlias(alias) ll = taurus.getLogLevel() if trace: taurus.setLogLevel(taurus.Debug) # self.debug('setModel("%s")'%model) if self._currF: #filename = str(self._currFile.absoluteFilePath()) filename = self._currF filename = os.path.realpath(filename) if os.path.isfile(filename): self.debug("Starting to parse %s" % filename) self.path = os.path.dirname(filename) factory = self.getGraphicsFactory(delayed=delayed) scene = jdraw_parser.parse(filename, factory) scene.setSelectionStyle(self._selectionStyle) self.debug("Obtained %s(%s)", type(scene).__name__, filename) if not scene: self.warning("TaurusJDrawSynopticsView.setModel(%s): Unable to parse %s!!!" % ( model, filename)) elif self.w_scene is None and scene.sceneRect(): self.w_scene = scene.sceneRect().width() self.h_scene = scene.sceneRect().height() else: self.debug('JDrawView.sceneRect() is NONE!!!') self.setScene(scene) self.scene().graphicItemSelected.connect(self._graphicItemSelected) self.scene().graphicSceneClicked.connect(self._graphicSceneClicked) # Qt.QApplication.instance().lastWindowClosed.connect(self.close) #It caused a # segfault! self.__modelsChanged() self.setWindowTitle(self.modelName) # The emitted signal contains the filename and a dictionary # with the name of items and its color self.emitColors() # get_item_colors(emit=True) self.fitting(True) else: self.setScene(None) #self.debug('out of setModel()') taurus.setLogLevel(ll)
def setUp(self): taurus.setLogLevel(taurus.Critical) for qt in _QtAPIs: if qt in sys.modules: self.QtAPI = qt break else: self.QtAPI = "PyQt4" self.opt_mods = ("QtDesigner", "QtNetwork", "Qt", "QtSvg", "QtUiTools", "QtWebKit", "Qwt5", "uic") # store a "snapshot" of the currently loaded modules self._orig_mods = set(sys.modules.keys()) # this import initializes Qt in case it is not loaded from taurus.external.qt import Qt self.__qt = Qt
def jdraw_view_main(): import sys import time import taurus.qt.qtgui.graphic taurus.setLogLevel(taurus.Info) from taurus.qt.qtgui.application import TaurusApplication app = TaurusApplication(sys.argv) #form = Qt.QDialog() # ly=Qt.QVBoxLayout(form) # container=Qt.QWidget() # ly.addWidget(container) # for m in sys.argv[1:]: #tv=TaurusJDrawSynopticsView(container, designMode=False) # tv.setModel(m) form = taurus.qt.qtgui.graphic.TaurusJDrawSynopticsView(designMode=False) form.show() # print '%s setModel(%s)'%(time.ctime(),sys.argv[1]) form.setModel(sys.argv[1]) form.setWindowTitle(sys.argv[1].rsplit('.', 1)[0]) sys.exit(app.exec_())
def jdraw_view_main(): import sys import time import taurus.qt.qtgui.graphic taurus.setLogLevel(taurus.Info) app = Qt.QApplication(sys.argv) #form = Qt.QDialog() # ly=Qt.QVBoxLayout(form) # container=Qt.QWidget() # ly.addWidget(container) # for m in sys.argv[1:]: #tv=TaurusJDrawSynopticsView(container, designMode=False) # tv.setModel(m) form = taurus.qt.qtgui.graphic.TaurusJDrawSynopticsView(designMode=False) form.show() # print '%s setModel(%s)'%(time.ctime(),sys.argv[1]) form.setModel(sys.argv[1]) form.setWindowTitle(sys.argv[1].rsplit('.', 1)[0]) #def kk(*args):print("\tgraphicItemSelected(%s)"%str(args)) #form.connect(form,Qt.SIGNAL("graphicItemSelected(QString)"), kk) form.fitting() sys.exit(app.exec_())
def setUp(self): taurus.setLogLevel(taurus.Critical) for qt in _QtAPIs: if qt in sys.modules: self.QtAPI = qt break else: self.QtAPI = "PyQt4" self.opt_mods = ("QtDesigner", "QtNetwork", "Qt", "QtSvg", "QtUiTools", "QtWebKit", "Qwt5", "uic") # store a "snapshot" of the currently loaded modules self._orig_mods = set(sys.modules.keys()) # auto initialize Qt by taurus using forcibly the self.QtAPI tauruscustomsettings.QT_AUTO_INIT = True tauruscustomsettings.QT_AUTO_API = self.QtAPI tauruscustomsettings.QT_AUTO_STRICT = True # this import initializes Qt in case it is not loaded from taurus.external.qt import Qt self.__qt = Qt
:param period: (int) period in ms """ self._period = period # update existing items if self.autoconnect() and self.plot_item is not None: for item in self.plot_item.listDataItems(): if hasattr(item, "setForcedReadPeriod"): item.setForcedReadPeriod(period) # emit valueChanged self.valueChanged.emit(period) if __name__ == "__main__": import taurus taurus.setLogLevel(taurus.Debug) import sys from taurus.qt.qtgui.application import TaurusApplication from taurus.qt.qtgui.tpg import TaurusTrendSet, DateAxisItem import pyqtgraph as pg # from taurus.qt.qtgui.tpg import ForcedReadTool app = TaurusApplication() w = pg.PlotWidget() axis = DateAxisItem(orientation="bottom") w = pg.PlotWidget() axis.attachToPlotItem(w.getPlotItem())
def setModel(self, model, alias=None, delayed=False, trace=False): #print "\n\n\n before set Model: \n\n" self.modelName = str(model) #print "\n Model: ", self.modelName self._currF = str(model) #print "\n\n Alias: ", alias if alias is not None: self.setAlias(alias) ll = taurus.getLogLevel() #print "\n\n LL:", ll, "\n\n" #print "\n\n TRACE: ", trace if trace: taurus.setLogLevel(taurus.Debug) #self.debug('setModel("%s")'%model) if self._currF: #filename = str(self._currFile.absoluteFilePath()) filename = self._currF #print "\n", filename filename = os.path.realpath(filename) #print "real path filename: ", filename if os.path.isfile(filename): #print "\n\n Jestem plikiem: ", filename self.debug("Starting to parse %s" % filename) #print "\n\nSPARSOWALEM\n\n" self.path = os.path.dirname(filename) #print "\n\n KATALOG: ", self.path factory = self.getGraphicsFactory(delayed=delayed) print "\n\n Zrobione factory ;)" scene = jdraw_parser.parse(filename, factory) print "\n\n filename and factory parsed" scene.setSelectionStyle(self._selectionStyle) self.debug("Obtained %s(%s)", type(scene).__name__, filename) if not scene: self.warning( "TaurusJDrawSynopticsView.setModel(%s): Unable to parse %s!!!" % (model, filename)) elif self.w_scene is None and scene.sceneRect(): self.w_scene = scene.sceneRect().width() self.h_scene = scene.sceneRect().height() else: self.debug('JDrawView.sceneRect() is NONE!!!') self.setScene(scene) for i in self.scene().items(): print "\n element: ", i #i.connect(i, Qt.SIGNAL('clicked()'), self.onClicked) #i.mousePressEvent(i, event) try: Qt.QObject.connect( i, Qt.SIGNAL("activated(const QString&)"), self._test) print "\n connected" except: print "exeption" Qt.QObject.connect(self.scene(), Qt.SIGNAL("graphicItemSelected(QString)"), self._graphicItemSelected) Qt.QObject.connect(self.scene(), Qt.SIGNAL("graphicSceneClicked(QPoint)"), self._graphicSceneClicked) #Qt.QObject.connect(Qt.QApplication.instance(), Qt.SIGNAL("lastWindowClosed()"), self.close) #It caused a segfault! self.modelsChanged() self.setWindowTitle(self.modelName) #The emitted signal contains the filename and a dictionary with the name of items and its color self.emitColors() #get_item_colors(emit=True) self.fitting(True) else: self.setScene(None) #self.debug('out of setModel()') taurus.setLogLevel(ll)
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])
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])
toolbar.set_toolbar([ ##('PDFs','icon-all.gif',[ #('Pdf Q1','icon-all.gif',lambda:launch('%s %s'%('kpdf','TC_Q1.pdf'))), #('Pdf Q2','icon-all.gif',lambda:launch('%s %s'%('kpdf','TC_Q2.pdf'))), #('Pdf Q3','icon-all.gif',lambda:launch('%s %s'%('kpdf','TC_Q3.pdf'))), #('Pdf Q4','icon-all.gif',lambda:launch('%s %s'%('kpdf','TC_Q4.pdf'))), ## ]), #('Archiving Viewer','Mambo-icon.ico', lambda:launch('mambo')), ('Show New Trend','qwtplot.png',table.open_new_trend), ]) toolbar.add_to_main_window(tmw,where=Qt.Qt.BottomToolBarArea) tmw.show() if args: table.updateSearch(*args) if '--range' in opts: tracer('Setting trend range to %s' % opts['--range']) table.trend.applyNewDates(opts['--range'].replace('_',' ').split(',')) return tmw if __name__ == "__main__": import sys if 'qapp' not in locals() and 'qapp' not in globals(): qapp = Qt.QApplication([]) import taurus taurus.setLogLevel('WARNING') t = main(args = sys.argv[1:]) sys.exit(qapp.exec_())
##('PDFs','icon-all.gif',[ #('Pdf Q1','icon-all.gif',lambda:launch('%s %s'%('kpdf','TC_Q1.pdf'))), #('Pdf Q2','icon-all.gif',lambda:launch('%s %s'%('kpdf','TC_Q2.pdf'))), #('Pdf Q3','icon-all.gif',lambda:launch('%s %s'%('kpdf','TC_Q3.pdf'))), #('Pdf Q4','icon-all.gif',lambda:launch('%s %s'%('kpdf','TC_Q4.pdf'))), ## ]), #('Archiving Viewer','Mambo-icon.ico', lambda:launch('mambo')), ('Show New Trend', 'qwtplot.png', table.open_new_trend), ]) toolbar.add_to_main_window(tmw, where=Qt.Qt.BottomToolBarArea) tmw.show() if args: table.updateSearch(*args) if '--range' in opts: tracer('Setting trend range to %s' % opts['--range']) table.trend.applyNewDates(opts['--range'].replace('_', ' ').split(',')) return tmw if __name__ == "__main__": import sys if 'qapp' not in locals() and 'qapp' not in globals(): qapp = Qt.QApplication([]) import taurus taurus.setLogLevel('WARNING') t = main(args=sys.argv[1:]) sys.exit(qapp.exec_())
def main(args): import sys, re, traceback, taurus print('args: %s' % str(args)) assert len(args)>1, '\n\nUsage:\n\t'\ '> python panel.py [a/device/name or synoptic.jdw] [--attrs] '\ '[attr_regexps] --comms [comm_regexps]' model = args[1] taurus.setLogLevel(taurus.core.util.Logger.Debug) app = Qt.QApplication(args) form = None VACCA_CONFIG = os.getenv('VACCA_CONFIG') if not VACCA_CONFIG: VACCA_CONFIG = fandango.objects.find_module('vaccagui') print('VACCA_CONFIG: %s' % VACCA_CONFIG) if VACCA_CONFIG: import vacca.utils as vu PROPS = vu.get_config_properties(VACCA_CONFIG) VACCA_DIR = WDIR = PROPS.get('VACCA_DIR', vu.VACCA_DIR) try: import default except: try: default = get_config_file( imp.find_module('vacca')[1] + '/default.py') except: traceback.print_exc() CONFIG = vu.get_config_file() if re.match(fandango.tango.retango, model): print 'loading a device panel' k, filters = '--attrs', fandango.defaultdict(list) for f in args[2:]: if f.startswith('--'): k = f.strip('-') else: filters[k].append(f) #(f,()) if k=='comms' else f) form = VaccaPanel(filters=filters) #palette=get_fullWhite_palette() form.setModel(model) elif model.lower().endswith('.jdw'): print 'loading a synoptic' import taurus.qt.qtgui.graphic as tqqg form = tqqg.TauJDrawSynopticsView( designMode=False, updateMode=tqqg.TauJDrawSynopticsView.NoViewportUpdate) #FullViewportUpdate, : AWFUL CPU USAGE!!!!!!!! #MinimalViewportUpdate, : Qt Defaults #SmartViewportUpdate, : ? #BoundingRectViewportUpdate, : ? #NoViewportUpdate : Tau defaults form.setModel(model) models = form.get_item_list() for m in models: m = str(m) if m.count('/') == 2: m += '/state' period = 120000. try: taurus.Attribute(m).changePollingPeriod(period) except: print '(%s).changePollingPeriod(%s): Failed: %s' % ( m, period, traceback.format_exc()) else: print('Unknown model: %s' % model) print 'showing ...' form.show() sys.exit(app.exec_())