Python traceback.print_exc() Examples

The following are 30 code examples of traceback.print_exc(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module traceback , or try the search function .
Example #1
Source File: GXDLMSReader.py    From Gurux.DLMS.Python with GNU General Public License v2.0 6 votes vote down vote up
def getReadOut(self):
        #pylint: disable=unidiomatic-typecheck, broad-except
        for it in self.client.objects:
            if type(it) == GXDLMSObject:
                print("Unknown Interface: " + it.objectType.__str__())
                continue
            if isinstance(it, GXDLMSProfileGeneric):
                continue

            self.writeTrace("-------- Reading " + str(it.objectType) + " " + str(it.name) + " " + it.description, TraceLevel.INFO)
            for pos in (it).getAttributeIndexToRead(True):
                try:
                    val = self.read(it, pos)
                    self.showValue(pos, val)
                except Exception as ex:
                    self.writeTrace("Error! Index: " + str(pos) + " " + str(ex), TraceLevel.ERROR)
                    self.writeTrace(str(ex), TraceLevel.ERROR)
                    if not isinstance(ex, (GXDLMSException, TimeoutException)):
                        traceback.print_exc() 
Example #2
Source File: zmirror.py    From zmirror with MIT License 6 votes vote down vote up
def cron_task_host():
    """定时任务宿主, 每分钟检查一次列表, 运行时间到了的定时任务"""
    while True:
        # 当全局开关关闭时, 自动退出线程
        if not enable_cron_tasks:
            if threading.current_thread() != threading.main_thread():
                exit()
            else:
                return

        sleep(60)
        try:
            task_scheduler.run()
        except:  # coverage: exclude
            errprint('ErrorDuringExecutingCronTasks')
            traceback.print_exc() 
Example #3
Source File: test_exception.py    From zmirror with MIT License 6 votes vote down vote up
def test_import_error_custom_func(self):
        restore_config_file()
        try:
            shutil.copy(zmirror_file('config_default.py'), zmirror_file('config.py'))
            try:
                self.reload_zmirror({"custom_text_rewriter_enable": True,
                                     "enable_custom_access_cookie_generate_and_verify": True,
                                     "identity_verify_required": True,
                                     })
            except:
                import traceback
                traceback.print_exc()
            os.remove(zmirror_file('config.py'))
        except:
            pass
        copy_default_config_file() 
Example #4
Source File: parser_mod.py    From Turku-neural-parser-pipeline with Apache License 2.0 6 votes vote down vote up
def launch(args,q_in,q_out):
    try:
        parser=parser_lib.NetworkParserWrapper(args.model,args.parser_dir)
    except:
        traceback.print_exc()
        sys.stderr.flush()
    while True:
        jobid,txt=q_in.get()
        if jobid=="FINAL":
            q_out.put((jobid,txt))
            return
        try:
            conllu=parser.parse_text(txt)
            if args.process_morpho == True:
                conllu=process_batch(conllu, detransfer=True)
            q_out.put((jobid,conllu))
        except:
            traceback.print_exc()
            sys.stderr.flush() 
Example #5
Source File: test_format.py    From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_format_docstrings():
    """
    Test if docstrings are well formatted.
    """
    # Disabled for now
    return True

    try:
        verify_format_docstrings()
    except SkipTest as e:
        import traceback
        traceback.print_exc(e)
        raise AssertionError(
            "Some file raised SkipTest on import, and inadvertently"
            " canceled the documentation testing."
        ) 
Example #6
Source File: mbusb_gui.py    From multibootusb with GNU General Public License v2.0 6 votes vote down vote up
def install_syslinux(self):
        try:
            try:
                self.install_syslinux_impl()
            finally:
                config.process_exist = None
                self.ui_enable_controls()
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            uninstall_distro.do_uninstall_distro(
                config.distro, iso_basename(config.image_path))
            o = io.StringIO()
            traceback.print_exc(None, o)
            QtWidgets.QMessageBox.information(
                self, 'install_syslinux() failed',
                o.getvalue())
            log("install_syslinux() failed.")
            log(o.getvalue()) 
Example #7
Source File: cookiejar_tp.py    From sawtooth-cookiejar with Apache License 2.0 6 votes vote down vote up
def main():
    '''Entry-point function for the cookiejar Transaction Processor.'''
    try:
        # Setup logging for this class.
        logging.basicConfig()
        logging.getLogger().setLevel(logging.DEBUG)

        # Register the Transaction Handler and start it.
        processor = TransactionProcessor(url=DEFAULT_URL)
        sw_namespace = _hash(FAMILY_NAME.encode('utf-8'))[0:6]
        handler = CookieJarTransactionHandler(sw_namespace)
        processor.add_handler(handler)
        processor.start()
    except KeyboardInterrupt:
        pass
    except SystemExit as err:
        raise err
    except BaseException as err:
        traceback.print_exc(file=sys.stderr)
        sys.exit(1) 
Example #8
Source File: events_client.py    From sawtooth-cookiejar with Apache License 2.0 6 votes vote down vote up
def main():
    '''Entry point function for the client CLI.'''

    filters = [events_pb2.EventFilter(key="address",
                                      match_string=
                                      COOKIEJAR_TP_ADDRESS_PREFIX + ".*",
                                      filter_type=events_pb2.
                                      EventFilter.REGEX_ANY)]

    try:
        # To listen to all events, pass delta_filters=None :
        #listen_to_events(delta_filters=None)
        listen_to_events(delta_filters=filters)
    except KeyboardInterrupt:
        pass
    except SystemExit as err:
        raise err
    except BaseException as err:
        traceback.print_exc(file=sys.stderr)
        sys.exit(1) 
Example #9
Source File: events_client.py    From sawtooth-cookiejar with Apache License 2.0 6 votes vote down vote up
def main():
    '''Entry point function for the client CLI.'''

    filters = [events_pb2.EventFilter(key="address",
                                      match_string=
                                      COOKIEJAR_TP_ADDRESS_PREFIX + ".*",
                                      filter_type=events_pb2.
                                      EventFilter.REGEX_ANY)]

    try:
        # To listen to all events, pass delta_filters=None :
        #listen_to_events(delta_filters=None)
        listen_to_events(delta_filters=filters)
    except KeyboardInterrupt:
        pass
    except SystemExit as err:
        raise err
    except BaseException as err:
        traceback.print_exc(file=sys.stderr)
        sys.exit(1) 
Example #10
Source File: gitter.py    From fishroom with GNU General Public License v3.0 6 votes vote down vote up
def test():
    gitter = Gitter(
        token="",
        rooms=(
            "57397795c43b8c60197322b9",
            "5739b957c43b8c6019732c0b",
        ),
        me=''
    )

    def response(msg):
        print(msg)
        gitter.send_msg(
            target=msg.receiver, content=msg.content, sender="fishroom")

    gitter.send_to_bus = response

    try:
        gitter.listen_message_stream(id_blacklist=("master_tuna_twitter", ))
    except Exception:
        import traceback
        traceback.print_exc() 
Example #11
Source File: services.py    From bioservices with GNU General Public License v3.0 6 votes vote down vote up
def post_one(self, query=None, frmt='json', **kargs):
        self._calls()
        self.logging.debug("BioServices:: Entering post_one function")
        if query is None:
            url = self.url
        else:
            url = '%s/%s' % (self.url, query)
        self.logging.debug(url)
        try:
            res = self.session.post(url, **kargs)
            self.last_response = res
            res = self._interpret_returned_request(res, frmt)
            try:
                return res.decode()
            except:
                self.logging.debug("BioServices:: Could not decode the response")
                return res
        except Exception as err:
            traceback.print_exc()
            return None 
Example #12
Source File: app.py    From botbuilder-python with MIT License 6 votes vote down vote up
def on_error(context: TurnContext, error: Exception):
    # This check writes out errors to console log .vs. app insights.
    # NOTE: In production environment, you should consider logging this to Azure
    #       application insights.
    print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
    traceback.print_exc()

    # Send a message to the user
    await context.send_activity("The bot encountered an error or bug.")
    await context.send_activity(
        "To continue to run this bot, please fix the bot source code."
    )
    # Send a trace activity if we're talking to the Bot Framework Emulator
    if context.activity.channel_id == "emulator":
        # Create a trace activity that contains the error object
        trace_activity = Activity(
            label="TurnError",
            name="on_turn_error Trace",
            timestamp=datetime.utcnow(),
            type=ActivityTypes.trace,
            value=f"{error}",
            value_type="https://www.botframework.com/schemas/error",
        )
        # Send a trace activity, which will be displayed in Bot Framework Emulator
        await context.send_activity(trace_activity) 
Example #13
Source File: app.py    From botbuilder-python with MIT License 6 votes vote down vote up
def on_error(context: TurnContext, error: Exception):
    # This check writes out errors to console log .vs. app insights.
    # NOTE: In production environment, you should consider logging this to Azure
    #       application insights.
    print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
    traceback.print_exc()

    # Send a message to the user
    await context.send_activity("The bot encountered an error or bug.")
    await context.send_activity(
        "To continue to run this bot, please fix the bot source code."
    )
    # Send a trace activity if we're talking to the Bot Framework Emulator
    if context.activity.channel_id == "emulator":
        # Create a trace activity that contains the error object
        trace_activity = Activity(
            label="TurnError",
            name="on_turn_error Trace",
            timestamp=datetime.utcnow(),
            type=ActivityTypes.trace,
            value=f"{error}",
            value_type="https://www.botframework.com/schemas/error",
        )
        # Send a trace activity, which will be displayed in Bot Framework Emulator
        await context.send_activity(trace_activity) 
Example #14
Source File: app.py    From botbuilder-python with MIT License 6 votes vote down vote up
def on_error(context: TurnContext, error: Exception):
    # This check writes out errors to console log .vs. app insights.
    # NOTE: In production environment, you should consider logging this to Azure
    #       application insights.
    print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
    traceback.print_exc()

    # Send a message to the user
    await context.send_activity("The bot encountered an error or bug.")
    await context.send_activity(
        "To continue to run this bot, please fix the bot source code."
    )
    # Send a trace activity if we're talking to the Bot Framework Emulator
    if context.activity.channel_id == "emulator":
        # Create a trace activity that contains the error object
        trace_activity = Activity(
            label="TurnError",
            name="on_turn_error Trace",
            timestamp=datetime.utcnow(),
            type=ActivityTypes.trace,
            value=f"{error}",
            value_type="https://www.botframework.com/schemas/error",
        )
        # Send a trace activity, which will be displayed in Bot Framework Emulator
        await context.send_activity(trace_activity) 
Example #15
Source File: extractor.py    From firmanal with MIT License 6 votes vote down vote up
def update_database(self, field, value):
        """
        Update a given field in the database.
        """
        ret = True
        if self.database:
            try:
                cur = self.database.cursor()
                cur.execute("UPDATE image SET " + field + "='" + value +
                            "' WHERE id=%s", (self.tag, ))
                self.database.commit()
            except BaseException:
                ret = False
                traceback.print_exc()
                self.database.rollback()
            finally:
                if cur:
                    cur.close()
        return ret 
Example #16
Source File: Udp_server.py    From rtp_cluster with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def handle_read(self, data, address, rtime, delayed = False):
        if len(data) > 0 and self.uopts.data_callback != None:
            self.stats[2] += 1
            if self.uopts.ploss_in_rate > 0.0 and not delayed:
                if random() < self.uopts.ploss_in_rate:
                    return
            if self.uopts.pdelay_in_max > 0.0 and not delayed:
                pdelay = self.uopts.pdelay_in_max * random()
                Timeout(self.handle_read, pdelay, 1, data, address, rtime.getOffsetCopy(pdelay), True)
                return
            try:
                self.uopts.data_callback(data, address, self, rtime)
            except Exception as ex:
                if isinstance(ex, SystemExit):
                    raise 
                print(datetime.now(), 'Udp_server: unhandled exception when processing incoming data')
                print('-' * 70)
                traceback.print_exc(file = sys.stdout)
                print('-' * 70)
                sys.stdout.flush() 
Example #17
Source File: tools.py    From OpenTrader with GNU Lesser General Public License v3.0 6 votes vote down vote up
def set_trace():
    """Call pdb.set_trace in the caller's frame.

    First restore sys.stdout and sys.stderr.  Note that the streams are
    NOT reset to whatever they were before the call once pdb is done!
    """
    import pdb
    for stream in 'stdout', 'stderr':
        output = getattr(sys, stream)
        orig_output = getattr(sys, '__%s__' % stream)
        if output != orig_output:
            # Flush the output before entering pdb
            if hasattr(output, 'getvalue'):
                orig_output.write(output.getvalue())
                orig_output.flush()
            setattr(sys, stream, orig_output)
    exc, tb = sys.exc_info()[1:]
    if tb:
        if isinstance(exc, AssertionError) and exc.args:
            # The traceback is not printed yet
            print_exc()
        pdb.post_mortem(tb)
    else:
        pdb.Pdb().set_trace(sys._getframe().f_back) 
Example #18
Source File: cmd2plus.py    From OpenTrader with GNU Lesser General Public License v3.0 6 votes vote down vote up
def set_trace():
    """Call pdb.set_trace in the caller's frame.

    First restore sys.stdout and sys.stderr.  Note that the streams are
    NOT reset to whatever they were before the call once pdb is done!
    """
    import pdb
    for stream in 'stdout', 'stderr':
        output = getattr(sys, stream)
        orig_output = getattr(sys, '__%s__' % stream)
        if output != orig_output:
            # Flush the output before entering pdb
            if hasattr(output, 'getvalue'):
                orig_output.write(output.getvalue())
                orig_output.flush()
            setattr(sys, stream, orig_output)
    exc, tb = sys.exc_info()[1:]
    if tb:
        if isinstance(exc, AssertionError) and exc.args:
            # The traceback is not printed yet
            print_exc()
        pdb.post_mortem(tb)
    else:
        pdb.Pdb().set_trace(sys._getframe().f_back) 
Example #19
Source File: concurrency.py    From dataflow with Apache License 2.0 6 votes vote down vote up
def run(self):
        nr_end = 0
        try:
            while True:
                task_id, data = self.data_queue.get()
                if task_id == DIE:
                    self.result_queue.put((task_id, data))
                    nr_end += 1
                    if nr_end == self.nr_producer:
                        return
                else:
                    self.ordered_container.put(task_id, data)
                    while self.ordered_container.has_next():
                        self.result_queue.put(self.ordered_container.get())
        except Exception as e:
            import traceback
            traceback.print_exc()
            raise e 
Example #20
Source File: GXDLMSReader.py    From Gurux.DLMS.Python with GNU General Public License v2.0 5 votes vote down vote up
def getProfileGenerics(self):
        #pylint: disable=broad-except,too-many-nested-blocks
        cells = []
        profileGenerics = self.client.objects.getObjects(ObjectType.PROFILE_GENERIC)
        for it in profileGenerics:
            self.writeTrace("-------- Reading " + str(it.objectType) + " " + str(it.name) + " " + it.description, TraceLevel.INFO)
            entriesInUse = self.read(it, 7)
            entries = self.read(it, 8)
            self.writeTrace("Entries: " + str(entriesInUse) + "/" + str(entries), TraceLevel.INFO)
            pg = it
            if entriesInUse == 0 or not pg.captureObjects:
                continue
            try:
                cells = self.readRowsByEntry(pg, 1, 1)
                if self.trace > TraceLevel.WARNING:
                    for rows in cells:
                        for cell in rows:
                            if isinstance(cell, bytearray):
                                self.writeTrace(GXByteBuffer.hex(cell) + " | ", TraceLevel.INFO)
                            else:
                                self.writeTrace(str(cell) + " | ", TraceLevel.INFO)
                        self.writeTrace("", TraceLevel.INFO)
            except Exception as ex:
                self.writeTrace("Error! Failed to read first row: " + str(ex), TraceLevel.ERROR)
                if not isinstance(ex, (GXDLMSException, TimeoutException)):
                    traceback.print_exc()
            try:
                start = datetime.datetime.now()
                end = start
                start.replace(hour=0, minute=0, second=0, microsecond=0)
                end.replace(minute=0, second=0, microsecond=0)
                cells = self.readRowsByRange(it, start, end)
                for rows in cells:
                    for cell in rows:
                        if isinstance(cell, bytearray):
                            print(GXByteBuffer.hex(cell) + " | ")
                        else:
                            self.writeTrace(str(cell) + " | ", TraceLevel.INFO)
                    self.writeTrace("", TraceLevel.INFO)
            except Exception as ex:
                self.writeTrace("Error! Failed to read last day: " + str(ex), TraceLevel.ERROR) 
Example #21
Source File: multiprocessor.py    From svviz with MIT License 5 votes vote down vote up
def _map(cls, methodName, initArgs, args, chunkNum, verbose):
    """ this takes care of most of the goodies, such as instantiating the Multiprocessor
    subclass, and performing the actual 'map' activity (as well as taking care of passing
    progress information back to the main process) """
    
    t0 = time.time()
    if initArgs != None:
        instance_ = cls(*initArgs)
    else:
        instance_ = cls()
    boundMethod = getattr(instance_, methodName)
    results = []

    try:
        tlast = time.time()
        
        for i, arg in enumerate(args):
            tnow = time.time()
            
            if verbose > 1 and (i%100==0 or i%(len(args)/20+1)==0 or (tnow-tlast)>1):
                if hasattr(_map, "q"):
                    _map.q.put((i, len(args), chunkNum))
                else:
                    print(i, "of", len(args), chunkNum)

                tlast = tnow
            results.append(boundMethod(arg))
        
        t1 = time.time()
        if 0 < verbose < 3:
            print("time elapsed:", t1-t0, "chunk:", chunkNum)
        return results
    except Exception as e:
        traceback.print_exc(file=sys.stdout)
        raise 
Example #22
Source File: runTests.py    From svviz with MIT License 5 votes vote down vote up
def _runTest(fn, description):
    print("\n\n -- running {} --\n\n".format(description))
    try:
        t0 = time.time()
        result = fn()
        t1 = time.time()
        result = [result[0], result[1], t1-t0]
    except Exception as e:
        print(" ** error running {}: {} **".format(description, e))
        print(traceback.print_exc())
        result = [False, str(e), -1]

    return result 
Example #23
Source File: flightdata.py    From AboveTustin with MIT License 5 votes vote down vote up
def refresh(self):
        try:
            #open the data url
            self.req = urlopen(self.data_url)

            #read data from the url
            self.raw_data = self.req.read()

            #load in the json
            self.json_data = json.loads(self.raw_data.decode())

            #get time from json
            self.time = datetime.fromtimestamp(self.parser.time(self.json_data))

            #load all the aircarft
            self.aircraft = self.parser.aircraft_data(self.json_data, self.time)

        except Exception:
            print("exception in FlightData.refresh():")
            traceback.print_exc() 
Example #24
Source File: zmirror.py    From zmirror with MIT License 5 votes vote down vote up
def cache_clean(is_force_flush=False):
    """
    清理程序运行中产生的垃圾, 在程序运行期间会被自动定期调用
    包括各种重写缓存, 文件缓存等
    默认仅清理过期的
    :param is_force_flush: 是否无视有效期, 清理所有缓存
    :type is_force_flush: bool
    """
    if enable_connection_keep_alive:
        connection_pool.clear(force_flush=is_force_flush)

    if local_cache_enable:
        cache.check_all_expire(force_flush_all=is_force_flush)

    if is_force_flush:
        try:
            url_to_use_cdn.clear()
            is_domain_match_glob_whitelist.cache_clear()
            is_mime_streamed.cache_clear()
            extract_real_url_from_embedded_url.cache_clear()
            embed_real_url_to_embedded_url.cache_clear()
            check_global_ua_pass.cache_clear()
            is_mime_represents_text.cache_clear()
            extract_mime_from_content_type.cache_clear()
            is_content_type_using_cdn.cache_clear()
            is_ua_in_whitelist.cache_clear()
            verify_ip_hash_cookie.cache_clear()
            is_denied_because_of_spider.cache_clear()
            is_ip_not_in_allow_range.cache_clear()
            # client_requests_text_rewrite.cache_clear()
            # extract_url_path_and_query.cache_clear()
        except:  # coverage: exclude
            errprint('ErrorWhenCleaningFunctionLruCache')
            traceback.print_exc() 
Example #25
Source File: zmirror.py    From zmirror with MIT License 5 votes vote down vote up
def append_ip_whitelist_file(ip_to_allow):
    """写入ip白名单到文件"""
    try:
        with open(zmirror_root(human_ip_verification_whitelist_file_path), 'a', encoding='utf-8') as fp:
            fp.write(ip_to_allow + '\n')
    except:  # coverage: exclude
        errprint('Unable to write whitelist file')
        traceback.print_exc() 
Example #26
Source File: zmirror.py    From zmirror with MIT License 5 votes vote down vote up
def preload_streamed_response_content_async(requests_response_obj, buffer_queue):
    """
    stream模式下, 预读远程响应的content
    :param requests_response_obj:
    :type buffer_queue: queue.Queue
    """
    for particle_content in requests_response_obj.iter_content(stream_transfer_buffer_size):
        try:
            buffer_queue.put(particle_content, timeout=10)
        except queue.Full:  # coverage: exclude
            traceback.print_exc()
            exit()
        if verbose_level >= 3: dbgprint('BufferSize', buffer_queue.qsize())
    buffer_queue.put(None, timeout=10)
    exit() 
Example #27
Source File: test_exception.py    From zmirror with MIT License 5 votes vote down vote up
def test_import_error_config(self):
        restore_config_file()
        try:
            self.reload_zmirror()
        except:
            import traceback
            traceback.print_exc()
            pass
        copy_default_config_file() 
Example #28
Source File: imager.py    From multibootusb with GNU General Public License v2.0 5 votes vote down vote up
def dd_iso_image(dd_progress_thread):
    try:
        dd_progress_thread.set_error(None)
        _dd_iso_image(dd_progress_thread)
    except:
        # config.imager_return = False
        o = io.StringIO()
        traceback.print_exc(None, o)
        log(o.getvalue())
        dd_progress_thread.set_error(o.getvalue()) 
Example #29
Source File: mbusb_gui.py    From multibootusb with GNU General Public License v2.0 5 votes vote down vote up
def onComboChange(self):
        """
        Detects and updates GUI with populated USB device details.
        :return:
        """
        self.ui.installed_distros.clear()
        config.usb_disk = osdriver.listbox_entry_to_device(
            self.ui.combo_drives.currentText())
        if config.usb_disk == 0 or config.usb_disk:
            # Get the GPT status of the disk and store it on a variable
            try:
                usb.gpt_device(config.usb_disk)
                config.imager_usb_disk \
                    = self.ui.combo_drives.currentText()
                config.usb_details \
                    = usb.details(config.usb_disk)
            except Exception as e:
                o = io.StringIO()
                traceback.print_exc(None, o)
                log(o.getvalue())
                QtWidgets.QMessageBox.critical(
                    self, "The disk/partition is not usable.",
                    str(e))
                self.ui.combo_drives.setCurrentIndex(0)
                # Above statement triggers call to this method.
                return
            log("Selected device " +
                            osdriver.usb_disk_desc(config.usb_disk))
            self.update_target_info()
            self.update_list_box(config.usb_disk)
            self.ui_update_persistence()
        else:
            self.ui.usb_dev.clear()
            self.ui.usb_vendor.clear()
            self.ui.usb_model.clear()
            self.ui.usb_size.clear()
            self.ui.usb_mount.clear()
            self.ui.usb_type.clear()
            self.ui.usb_fs.clear()
            log("No USB disk found...") 
Example #30
Source File: mbusb_gui.py    From multibootusb with GNU General Public License v2.0 5 votes vote down vote up
def onFsckClick(self, fsck_func):
        try:
            self.onFsckClick_impl(fsck_func)
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            o = io.StringIO()
            traceback.print_exc(None, o)
            QtWidgets.QMessageBox.information(
                self, 'Failed to run fsck',
                o.getvalue())