python类print_exc()的实例源码

proxy.py 文件源码 项目:backend.ai-client-py 作者: lablup 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def proxy(args):
    '''
    Run a non-encyprted non-authorized API proxy server.
    Use this only for development and testing!
    '''
    print_info('Starting an insecure API proxy at http://{0}:{1}'
               .format(args.bind, args.port))
    try:
        addr = (args.bind, args.port)
        httpd = http.server.HTTPServer(addr, APIProxyHandler)
        httpd.serve_forever()
    except (KeyboardInterrupt, SystemExit):
        print()
        print_info('Terminated.')
    except:
        print_fail('Unexpected error!')
        traceback.print_exc()
generator.py 文件源码 项目:flask-apidoc 作者: ipconfiger 项目源码 文件源码 阅读 42 收藏 0 点赞 0 评论 0
def main():
    sys.path.append(os.getcwd())
    if len(sys.argv) < 2:
        print "Missing argument: mod_name:<Flask App> for Example manager:app"
        sys.exit(1)
    if len(sys.argv) > 2:
        filter_arr = sys.argv[2].split(',')
    else:
        filter_arr = None
    import_str = sys.argv[1]
    try:
        mod_name, var_name = import_str.split(":")
        mod = __import__(mod_name, globals(), locals(), fromlist=[var_name, ])
        app = getattr(mod, var_name)
        g = Generator(app, filters=filter_arr)
        g.prepare()
        print g.generate_markdown()
        sys.exit(0)
    except Exception as e:
        traceback.print_exc()
        print "Can not import Flask app from argument", import_str
        sys.exit(1)
zmirror.py 文件源码 项目:zmirror 作者: aploium 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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()
test_exception.py 文件源码 项目:zmirror 作者: aploium 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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()
global_functions.py 文件源码 项目:TACTIC-Handler 作者: listyque 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def catch_error(func):
    def __tryexcept__(*args, **kwargs):

        try:
            func(*args, **kwargs)
        except Exception as expected:
            traceback.print_exc(file=sys.stdout)
            stacktrace = traceback.format_exc()

            exception = {
                'exception': expected,
                'stacktrace': stacktrace,
            }

            stacktrace_handle(exception)

    return __tryexcept__
taiwan_stock.py 文件源码 项目:stockcmd 作者: zzzaaa12 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def get_data(self, profile):
        self.data = []
        if profile['show_twse_index']:
            self.add_tw_future()

        self.create_stock_list(profile['show_user_list'])
        self.create_query_list(profile['show_twse_index'])
        # self.create_query_url(profile['show_twse_index'])

        try:
            for i in self.query_list:
                self.query_stock_info(i)
                self.parse_json_data()
        except:
            traceback.print_exc()
            return False

        return True
rackspace.py 文件源码 项目:FRG-Crowdsourcing 作者: 97amarnathk 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def _upload_file_to_rackspace(self, file, container, attempt=0):
        """Upload file to rackspace."""
        try:
            chksum = pyrax.utils.get_checksum(file)
            self.cf.upload_file(container,
                                file,
                                obj_name=secure_filename(file.filename),
                                etag=chksum)
            return True
        except Exception as e:
            print "Uploader exception"  # TODO: Log this!
            traceback.print_exc()
            attempt += 1
            if (attempt < 3):
                time.sleep(1)   # Wait one second and try again
                return self._upload_file_to_rackspace(file, container, attempt)
            else:
                print "Tried to upload two times. Failed!"   # TODO: Log this!
                raise
rackspace.py 文件源码 项目:FRG-Crowdsourcing 作者: 97amarnathk 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def _lookup_url(self, endpoint, values):
        """Return Rackspace URL for object."""
        try:
            # Create failover urls for avatars
            if '_avatar' in values['filename']:
                failover_url = url_for('static',
                                       filename='img/placeholder.user.png')
            else:
                failover_url = url_for('static',
                                       filename='img/placeholder.project.png')
            cont = self.get_container(values['container'])
            if cont.cdn_enabled:
                return "%s/%s" % (cont.cdn_ssl_uri, values['filename'])
            else:
                msg = ("Rackspace Container %s was not public"
                       % values['container'])
                current_app.logger.warning(msg)
                cont.make_public()
                return "%s/%s" % (cont.cdn_ssl_uri, values['filename'])
        except:
            current_app.logger.error(traceback.print_exc())
            return failover_url
Owner.py 文件源码 项目:youtube 作者: FishyFing 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def load(self, *, cog_name: str):
        """Loads a module
        Example: load mod"""
        module = cog_name.strip()
        if "modules." not in module:
            module = "modules." + module
        try:
            self._load_cog(module)
        except CogNotFoundError:
            await ctx.send("That cog could not be found.")
        except CogLoadError as e:
            logger.exception(e)
            traceback.print_exc()
            await ctx.send("There was an issue loading the cog. Check"
                           " your console or logs for more information.")
        except Exception as e:
            logger.exception(e)
            traceback.print_exc()
            await ctx.send('Cog was found and possibly loaded but '
                           'something went wrong. Check your console '
                           'or logs for more information.')
        else:
            set_cog(module, True)
            await self.disable_commands()
            await ctx.send("The cog has been loaded.")
Owner.py 文件源码 项目:youtube 作者: FishyFing 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def unload(self, *, cog_name: str):
        """Unloads a module
        Example: unload mod"""
        module = cog_name.strip()
        if "modules." not in module:
            module = "modules." + module
        if not self._does_cogfile_exist(module):
            await ctx.send("That cog file doesn't exist. I will not"
                           " turn off autoloading at start just in case"
                           " this isn't supposed to happen.")
        else:
            set_cog(module, False)
        try:  # No matter what we should try to unload it
            self._unload_cog(module)
        except OwnerUnloadWithoutReloadError:
            await ctx.send("I cannot allow you to unload the Owner plugin"
                           " unless you are in the process of reloading.")
        except CogUnloadError as e:
            logger.exception(e)
            traceback.print_exc()
            await ctx.send('Unable to safely unload that cog.')
        else:
            await ctx.send("The cog has been unloaded.")
sublime_plugin.py 文件源码 项目:TerminalView 作者: Wramberg 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def on_api_ready():
    global api_ready
    api_ready = True

    for m in list(sys.modules.values()):
        if "plugin_loaded" in m.__dict__:
            try:
                m.plugin_loaded()
            except:
                traceback.print_exc()

    # Synthesize an on_activated call
    w = sublime.active_window()
    if w:
        view_id = sublime_api.window_active_view(w.window_id)
        if view_id != 0:
            try:
                on_activated(view_id)
            except:
                traceback.print_exc()
input_data.py 文件源码 项目:IntroToDeepLearning 作者: robb-brown 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def __init__(self, images, labels, fake_data=False):
    if fake_data:
      self._num_examples = 10000
    else:
      assert images.shape[0] == labels.shape[0], (
          "images.shape: %s labels.shape: %s" % (images.shape,
                                                 labels.shape))
      self._num_examples = images.shape[0]

      # Convert shape from [num examples, rows, columns, depth]
      # to [num examples, rows*columns] (assuming depth == 1)
      self.imageShape = images.shape[1:]
      self.imageChannels = self.imageShape[2]

      images = images.reshape(images.shape[0],
                              images.shape[1] * images.shape[2] * images.shape[3])
      # Convert from [0, 255] -> [0.0, 1.0].
      images = images.astype(numpy.float32)
      images = numpy.multiply(images, 1.0 / 255.0)
    self._images = images
    self._labels = labels
    try:
      if len(numpy.shape(self._labels)) == 1:
        self._labels = dense_to_one_hot(self._labels,len(numpy.unique(self._labels)))
    except:
      traceback.print_exc()
    self._epochs_completed = 0
    self._index_in_epoch = 0
input_data.py 文件源码 项目:IntroToDeepLearning 作者: robb-brown 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def __init__(self, images, labels, fake_data=False):
    if fake_data:
      self._num_examples = 10000
    else:
      assert images.shape[0] == labels.shape[0], (
          "images.shape: %s labels.shape: %s" % (images.shape,
                                                 labels.shape))
      self._num_examples = images.shape[0]

      # Convert shape from [num examples, rows, columns, depth]
      # to [num examples, rows*columns] (assuming depth == 1)
      self.imageShape = images.shape[1:]
      self.imageChannels = self.imageShape[2]

      images = images.reshape(images.shape[0],
                              images.shape[1] * images.shape[2] * images.shape[3])
      # Convert from [0, 255] -> [0.0, 1.0].
      images = images.astype(numpy.float32)
      images = numpy.multiply(images, 1.0 / 255.0)
    self._images = images
    self._labels = labels
    try:
      if len(numpy.shape(self._labels)) == 1:
        self._labels = dense_to_one_hot(self._labels,len(numpy.unique(self._labels)))
    except:
      traceback.print_exc()
    self._epochs_completed = 0
    self._index_in_epoch = 0
query_handler.py 文件源码 项目:almond-nnparser 作者: Stanford-Mobisocial-IoT-Lab 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def _do_run_query(self, language, tokenized, limit):
        tokens, values, parse = tokenized
        print("Input", tokens, values)

        results = []
        config = language.config
        grammar = config.grammar
        with language.session.as_default():
            with language.session.graph.as_default():
                input, input_len = vectorize(tokens, config.dictionary, config.max_length)
                parse_vector = vectorize_constituency_parse(parse, config.max_length, input_len)
                input_batch, input_length_batch, parse_batch = [input], [input_len], [parse_vector]
                sequences = language.model.predict_on_batch(language.session, input_batch, input_length_batch, parse_batch)
                assert len(sequences) == 1

                for i, decoded in enumerate(sequences[0]):
                    if i >= limit:
                        break
                    decoded = list(decoded)
                    try:
                        decoded = decoded[:decoded.index(grammar.end)]
                    except ValueError:
                        pass
                    decoded = [grammar.tokens[x] for x in decoded]
                    print("Beam", i+1, decoded)
                    try:
                        json_rep = dict(answer=json.dumps(json_syntax.to_json(decoded, grammar, values)), prob=1./len(sequences[0]), score=1)
                    except Exception as e:
                        print("Failed to represent " + str(decoded) + " as json", e)
                        traceback.print_exc(file=sys.stdout)
                        continue
                    results.append(json_rep)
        return results
OSC3.py 文件源码 项目:pyOSC3 作者: Qirky 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def handle_error(self, request, client_address):
        """Handle an exception in the Server's callbacks gracefully.
        Writes the error to sys.stderr and, if the error_prefix (see setSrvErrorPrefix()) is set,
        sends the error-message as reply to the client
        """
        (e_type, e) = sys.exc_info()[:2]
        self.printErr("%s on request from %s: %s" % (e_type.__name__, getUrlStr(client_address), str(e)))

        if self.print_tracebacks:
            import traceback
            traceback.print_exc() # XXX But this goes to stderr!

        if len(self.error_prefix):
            self.sendOSCerror("%s: %s" % (e_type.__name__, str(e)), client_address)
OSC2.py 文件源码 项目:pyOSC3 作者: Qirky 项目源码 文件源码 阅读 52 收藏 0 点赞 0 评论 0
def handle_error(self, request, client_address):
        """Handle an exception in the Server's callbacks gracefully.
        Writes the error to sys.stderr and, if the error_prefix (see setSrvErrorPrefix()) is set,
        sends the error-message as reply to the client
        """
        (e_type, e) = sys.exc_info()[:2]
        self.printErr("%s on request from %s: %s" % (e_type.__name__, getUrlStr(client_address), str(e)))

        if self.print_tracebacks:
            import traceback
            traceback.print_exc() # XXX But this goes to stderr!

        if len(self.error_prefix):
            self.sendOSCerror("%s: %s" % (e_type.__name__, str(e)), client_address)
__init__.py 文件源码 项目:coa_tools 作者: ndee85 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def register():
    import bpy.utils.previews
    pcoll2 = bpy.utils.previews.new() 
    pcoll2.my_previews = ()
    preview_collections["coa_thumbs"] = pcoll2

    pcoll = bpy.utils.previews.new()
    pcoll.my_previews = ()
    my_icons_dir = os.path.join(os.path.dirname(__file__),"icons")
    pcoll.load("donate_icon", os.path.join(my_icons_dir,"donate_icon.png"),'IMAGE')
    pcoll.load("twitter_icon", os.path.join(my_icons_dir,"twitter_icon.png"),'IMAGE')
    pcoll.load("db_icon", os.path.join(my_icons_dir,"db_icon.png"),'IMAGE')

    preview_collections["main"] = pcoll
    preview_collections_pie["main"] = pcoll


    try: bpy.utils.register_module(__name__)
    except: traceback.print_exc()

    print("Registered {} with {} modules".format(bl_info["name"], len(modules)))

    bpy.types.Object.coa_anim_collections = bpy.props.CollectionProperty(type=AnimationCollections)
    bpy.types.Object.coa_uv_default_state = bpy.props.CollectionProperty(type=UVData)
    bpy.types.Object.coa_slot = bpy.props.CollectionProperty(type=SlotData)

    bpy.types.Scene.coa_ticker = bpy.props.IntProperty()
    bpy.types.WindowManager.coa_update_uv = bpy.props.BoolProperty(default=False)
    kc = bpy.context.window_manager.keyconfigs.addon
    if kc:
        km = kc.keymaps.new(name="3D View", space_type="VIEW_3D")
        kmi = km.keymap_items.new('view3d.move', 'MIDDLEMOUSE', 'PRESS')
        kmi.active = False

    bpy.app.handlers.frame_change_post.append(update_sprites)    
    bpy.app.handlers.scene_update_pre.append(scene_update)
    bpy.app.handlers.load_post.append(coa_startup)

    register_keymaps()
_dummy_thread.py 文件源码 项目:python- 作者: secondtonone1 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def start_new_thread(function, args, kwargs={}):
    """Dummy implementation of _thread.start_new_thread().

    Compatibility is maintained by making sure that ``args`` is a
    tuple and ``kwargs`` is a dictionary.  If an exception is raised
    and it is SystemExit (which can be done by _thread.exit()) it is
    caught and nothing is done; all other exceptions are printed out
    by using traceback.print_exc().

    If the executed function calls interrupt_main the KeyboardInterrupt will be
    raised when the function returns.

    """
    if type(args) != type(tuple()):
        raise TypeError("2nd arg must be a tuple")
    if type(kwargs) != type(dict()):
        raise TypeError("3rd arg must be a dict")
    global _main
    _main = False
    try:
        function(*args, **kwargs)
    except SystemExit:
        pass
    except:
        import traceback
        traceback.print_exc()
    _main = True
    global _interrupt
    if _interrupt:
        _interrupt = False
        raise KeyboardInterrupt
libmilter.py 文件源码 项目:sipxecs-voicemail-transcription 作者: andrewsauder 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
def run(self):
        self._sockLock = DummyLock()
        while True:
            buf = ''
            try:
                buf = self.transport.recv(MILTER_CHUNK_SIZE)
            except AttributeError:
                # Socket has been closed
                pass
            except socket.error:
                pass
            except socket.timeout:
                pass
            if not buf:
                try:
                    self.transport.close()
                except:
                    pass
                self.connectionLost()
                break
            try:
                self.dataReceived(buf)
            except Exception as e:
                self.log('466 AN EXCEPTION OCCURED IN %s: %s' % (self.id , e))
                if DEBUG:
                    traceback.print_exc()
                    debug('469 AN EXCEPTION OCCURED: %s' % e , 1 , self.id)
                self.send(TEMPFAIL)
                self.connectionLost()
                break
# }}}

# class ForkMixin {{{
libmilter.py 文件源码 项目:sipxecs-voicemail-transcription 作者: andrewsauder 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def run(self):
        self._sockLock = DummyLock()
        while True:
            buf = ''
            try:
                buf = self.transport.recv(MILTER_CHUNK_SIZE)
            except AttributeError:
                # Socket has been closed
                pass
            except socket.error:
                pass
            except socket.timeout:
                pass
            if not buf:
                try:
                    self.transport.close()
                except:
                    pass
                self.connectionLost()
                break
            try:
                self.dataReceived(buf)
            except Exception as e:
                self.log('508 AN EXCEPTION OCCURED IN %s: %s' % (self.id , e))
                if DEBUG:
                    traceback.print_exc()
                    debug('511 AN EXCEPTION OCCURED: %s' % e , 1 , self.id)
                self.send(TEMPFAIL)
                self.connectionLost()
                break
        #self.log('Exiting child process')
# }}}

# class MilterProtocol {{{


问题


面经


文章

微信
公众号

扫码关注公众号