Python traceback 模块,print_exc() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用traceback.print_exc()

项目:monasca-transform    作者:openstack    | 项目源码 | 文件源码
def _spawn_transform_service(self):
        """Launch transform service and get pid."""
        status = 0
        pid = os.fork()
        if pid == 0:
            try:
                os.setsid()
                # start transform service
                launcher = oslo_service.service.launch(
                    self.conf,
                    transform_service.Transform(),
                    workers=1)
                status = launcher.wait()
            except SystemExit as exc:
                traceback.print_exc()
                status = exc.code
            except BaseException:
                try:
                    traceback.print_exc()
                except BaseException:
                    print("Could not print traceback")
                status = 2
            os._exit(status or 0)
        return pid
项目:core-framework    作者:RedhawkSDR    | 项目源码 | 文件源码
def _config(props, category=None, disable_existing_loggers=1):
  logging.shutdown()

  # critical section
  # patterned after from logging.config... 
  logging._acquireLock()
  try:
     logging._handlers.clear()
     del logging._handlerList[:]
     # Handlers add themselves to logging._handlers
     handlers = _install_handlers(props)
     _install_loggers(props, handlers, category, disable_existing_loggers)
  except Exception as e:
    traceback.print_exc()
    raise e
  finally:
    logging._releaseLock()
项目:coa_tools    作者:ndee85    | 项目源码 | 文件源码
def unregister():
    for pcoll in preview_collections.values():
        bpy.utils.previews.remove(pcoll)
    preview_collections.clear()

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

    print("Unregistered {}".format(bl_info["name"]))
    bpy.context.window_manager.coa_running_modal = False

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

    unregister_keymaps()
项目:facerecognition    作者:guoxiaolu    | 项目源码 | 文件源码
def ftp_upload(ftp, remotefile, localfile):
    #f = open(localpath, "rb")
    #filename = os.path.split(localpath)[-1]
    try:
        #bufsize = 1024
        #localpath_file = os.listdir(localpath)
        #for filename in localpath_file:
        #fp = open(filename, 'rb')
        fp = open(localfile,'rb')
        ftp.storbinary('STOR ' + remotefile, fp)  # ????
        ftp.set_debuglevel(0)
        fp.close()  # ????
        #ftp.quit()
        print('????')

    except Exception as e:
        traceback.print_exc()
项目:core-framework    作者:RedhawkSDR    | 项目源码 | 文件源码
def _cleanup_domain():
    try:
        if globals().has_key('currentdomain'):
            __terminate_process( globals()['currentdomain'].process)
            x = globals().pop('currentdomain')
            if x : del x
    except:
        traceback.print_exc()
        pass
    if globals().has_key('currentdevmgrs'):
        for x in globals()['currentdevmgrs']:
            try:
                __terminate_process(x.process)
            except:
                traceback.print_exc()
                pass
        x = globals().pop('currentdevmgrs')
        if x : del x
项目:human-rl    作者:gsastry    | 项目源码 | 文件源码
def action_label_counts(directory, data_loader, n_actions=18, n=None):
    episode_paths = frame.episode_paths(directory)
    label_counts = [0, 0]
    action_label_counts = [[0, 0] for i in range(n_actions)]
    if n is not None:
        np.random.shuffle(episode_paths)
        episode_paths = episode_paths[:n]
    for episode_path in tqdm.tqdm(episode_paths):
        try:
            features, labels = data_loader.load_features_and_labels([episode_path])
        except:
            traceback.print_exc()
        else:
            for label in range(len(label_counts)):
                label_counts[label] += np.count_nonzero(labels == label)
                for action in range(n_actions):
                    actions = np.reshape(np.array(features["action"]), [-1])
                    action_label_counts[action][label] += np.count_nonzero(
                        np.logical_and(labels == label, actions == action))
    return label_counts, action_label_counts
项目:vscode-azurecli    作者:Microsoft    | 项目源码 | 文件源码
def _install_modules(command_table):
    for cmd in command_table:
        command_table[cmd].load_arguments()

    try:
        mods_ns_pkg = import_module('azure.cli.command_modules')
        installed_command_modules = [modname for _, modname, _ in
                                     pkgutil.iter_modules(mods_ns_pkg.__path__)
                                     if modname not in BLACKLISTED_MODS]
    except ImportError:
        pass
    for mod in installed_command_modules:
        try:
            mod = import_module('azure.cli.command_modules.' + mod)
            mod.load_params(mod)
            mod.load_commands()

        except Exception:  # pylint: disable=broad-except
            print("Error loading: {}".format(mod), file=stderr)
            traceback.print_exc(file=stderr)
    _update_command_definitions(command_table)
项目:ComicSpider    作者:QuantumLiu    | 项目源码 | 文件源码
def get_info(self):
        '''
        ????????????url???url
        Get informations of the comic
        return:
            comic title,description,cover url,chapters' urls
        '''
        headers={'use-agent':"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",'Referer':'http://manhua.dmzj.com/tags/s.shtml'}
        root='http://manhua.dmzj.com'
        r_title=r'<span class="anim_title_text"><a href=".*?"><h1>(.*?)</h1></a></span>'
        r_des=r'<meta name=\'description\' content=".*?(??.*?)"/>'#????
        r_cover=r'src="(.*?)" id="cover_pic"/></a>'#??url??
        r_cb=r'<div class="cartoon_online_border" >([\s\S]*?)<div class="clearfix"></div>'#??border
        r_cs=r'<li><a title="(.*?)" href="(.*?)" .*?>.*?</a>'#??????
        try:
            text=requests.get(self.comic_url,headers=headers).text
        except ConnectionError:
            traceback.print_exc()
            raise ConnectionError
        title=re.findall(r_title,text)[0]
        cb=re.findall(r_cb,text)[0]
        chapter_urls=[(c[0],root+c[1]+'#@page=1') for c in re.findall(r_cs,cb)]
        cover_url=re.findall(r_cover,text)[0]
        des=re.findall(r_des,text)
        return title,des,cover_url,chapter_urls
项目:ComicSpider    作者:QuantumLiu    | 项目源码 | 文件源码
def print_chapters(self,show=False):
        '''
        ??????
        Display infos of chapters.
        '''
        headers={'use-agent':"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",'Referer':'http://manhua.dmzj.com/tags/s.shtml'}
        text='There are {n} chapters in comic {c}:\n{chs}'.format(n=self.chapter_num,c=self.comic_title,chs='\n'.join([info[0] for info in self.chapter_urls]))
        print(text)
        if show:
            try:
                res=requests.get(self.cover,headers=headers)
                if b'403' in res.content:
                    raise ValueError('Got cover img failed')
                out=BytesIO(res.content)
                out.seek(0)
                Image.open(out).show()
            except (ConnectionError,ValueError):
                traceback.print_exc()
        return text
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def _run_exitfuncs():
    """run any registered exit functions

    _exithandlers is traversed in reverse order so functions are executed
    last in, first out.
    """

    exc_info = None
    while _exithandlers:
        func, targs, kargs = _exithandlers.pop()
        try:
            func(*targs, **kargs)
        except SystemExit:
            exc_info = sys.exc_info()
        except:
            import traceback
            print >> sys.stderr, "Error in atexit._run_exitfuncs:"
            traceback.print_exc()
            exc_info = sys.exc_info()

    if exc_info is not None:
        raise exc_info[0], exc_info[1], exc_info[2]
项目:git-of-theseus    作者:erikbern    | 项目源码 | 文件源码
def get_file_histogram(commit, path):
    h = {}
    try:
        for old_commit, lines in repo.blame(commit, path):
            cohort = commit2cohort.get(old_commit.hexsha, "MISSING")
            h[cohort] = h.get(cohort, 0) + len(lines)

            if old_commit.hexsha in commit2timestamp:
                h[old_commit.hexsha] = h.get(old_commit.hexsha, 0) + len(lines)
            _, ext = os.path.splitext(path)

            h[ext] = h.get(ext, 0) + len(lines)
    except KeyboardInterrupt:
        raise
    except:
        traceback.print_exc()
    return h
项目:stackimpact-python    作者:stackimpact    | 项目源码 | 文件源码
def test_add_exception(self):
        stackimpact._agent = None
        agent = stackimpact.start(
            dashboard_address = 'http://localhost:5001',
            agent_key = 'key1',
            app_name = 'TestPythonApp',
            debug = True
        )
        agent.error_reporter.start()

        try:
            raise ValueError('test_exc_1')
        except:
            traceback.print_exc()

        time.sleep(1.1)

        profile_handled_exc = agent.error_reporter.profile
        #print(profile_handled_exc)

        self.assertTrue('ValueError: test_exc_1' in str(profile_handled_exc))
        self.assertTrue('test_add_exception' in str(profile_handled_exc))

        agent.destroy()
项目:bitcoin-trading-system    作者:vinicius-ronconi    | 项目源码 | 文件源码
def execute(self):
        try:
            self.system.run()
        except (ReadTimeout, ConnectionError, JSONDecodeError):
            pass
        except exceptions.TradingSystemException as e:
            curr = datetime.now()
            print('{time} - {text}'.format(time=curr.strftime('%Y-%m-%d %H:%M:%S'), text=str(e)))
        except Exception as e:
            curr = datetime.now()
            print('{time} - {text} - {args}'.format(time=curr.strftime('%Y-%m-%d %H:%M:%S'), text=str(e), args=e.args))
            traceback.print_exc()

        if self.interval:
            threading.Timer(self.interval, self.execute).start()
项目:dl4mt-multi    作者:nyu-dl    | 项目源码 | 文件源码
def call_script(model_path, config, proto, eval_script,
                num_process=10, normalize=True):
    '''
    open pipe and call the script
    '''
    try:
        subprocess.call(
            " python {} {} --config={} "
            " --proto={} "
            " -p {} {}".format(
                eval_script, model_path, config,
                proto, num_process,
                ' -n ' if normalize else ''),
            shell=True)
    except:
        traceback.print_exc(file=sys.stdout)
        print 'error in call_bleu_script()'
    print model_path
项目:bap-ida-python    作者:BinaryAnalysisPlatform    | 项目源码 | 文件源码
def run_handlers(self, event):
        assert event in self.observers
        handlers = []
        instance_handlers = {
            'instance_canceled': self._on_cancel,
            'instance_failed':   self._on_failed,
            'instance_finished': self._on_finish,
        }

        handlers += self.observers[event]
        handlers += instance_handlers.get(event, [])

        failures = 0
        for handler in handlers:
            try:
                handler(self)
            except:  # pylint: disable=bare-except
                failures += 1
                idc.Message("BAP> {0} failed because {1}\n".
                            format(self.action, str(sys.exc_info()[1])))
                traceback.print_exc()
        if failures != 0:
            idc.Warning("Some BAP handlers failed")
项目:bitcoin-arbitrage    作者:ucfyao    | 项目源码 | 文件源码
def get_info(self):
        """Get balance"""
        try:
            accounts = exchange_api.exchange_get_account()
        except Exception as e:
            traceback.print_exc()
            exchange_api.init_broker()
            return

        if accounts:
            self.cny_balance = 0
            self.btc_balance = 0
            self.cny_frozen = 0
            self.btc_frozen = 0

            for account in accounts:
                self.btc_balance += account.available_btc
                self.cny_balance += account.available_cny
                self.btc_frozen +=  account.frozen_cny
                self.cny_frozen +=  account.frozen_btc
项目:bitcoin-arbitrage    作者:ucfyao    | 项目源码 | 文件源码
def get_info(self):
        """Get balance"""
        try:
            response = self.market.accountInfo()
            if response and "code" in response:
                logging.warn(response)
                return False
                raise TradeException(response["message"])
            if response:
                self.btc_balance = float(response["available_btc_display"])
                self.cny_balance = float(response["available_cny_display"])
                self.btc_frozen = float(response["frozen_btc_display"])
                self.cny_frozen = float(response["frozen_cny_display"])
        except  Exception as ex:
            logging.warn("get_info failed :%s" % ex)
            traceback.print_exc()

            return False
项目:bitcoin-arbitrage    作者:ucfyao    | 项目源码 | 文件源码
def httpPost(url,resource,params):
    headers = {
        "Content-type" : "application/x-www-form-urlencoded",
    }
    try :
        conn = httplib.HTTPSConnection(url, timeout=10)
        temp_params = urllib.parse.urlencode(params)
        conn.request("POST", resource, temp_params, headers)
        response = conn.getresponse()
        data = response.read().decode('utf-8')
        params.clear()
        conn.close()
        return data
    except:
    # except Exception,e:  
        # print(Exception,":",e)
        traceback.print_exc()
        return False
项目:bitcoin-arbitrage    作者:ucfyao    | 项目源码 | 文件源码
def send_email(subject, msg):
    import smtplib

    message = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s\r\n" % (config.EMAIL_HOST_USER, ", ".join(config.EMAIL_RECEIVER), subject, msg)
    try:
        smtpserver = smtplib.SMTP(config.EMAIL_HOST)
        smtpserver.set_debuglevel(0)
        smtpserver.ehlo()
        smtpserver.starttls()
        smtpserver.ehlo
        smtpserver.login(config.EMAIL_HOST_USER, config.EMAIL_HOST_PASSWORD)
        smtpserver.sendmail(config.EMAIL_HOST_USER, config.EMAIL_RECEIVER, message)
        smtpserver.quit()  
        smtpserver.close() 
        logging.info("send mail success")      
    except:
        logging.error("send mail failed")
        traceback.print_exc()
项目:Flask_Blog    作者:sugarguo    | 项目源码 | 文件源码
def run(self):
        """Runs the handler, flushes the streams, and ends the request."""
        try:
            protocolStatus, appStatus = self.server.handler(self)
        except:
            traceback.print_exc(file=self.stderr)
            self.stderr.flush()
            if not self.stdout.dataWritten:
                self.server.error(self)

            protocolStatus, appStatus = FCGI_REQUEST_COMPLETE, 0

        if __debug__: _debug(1, 'protocolStatus = %d, appStatus = %d' %
                             (protocolStatus, appStatus))

        try:
            self._flush()
            self._end(appStatus, protocolStatus)
        except socket.error, e:
            if e[0] != errno.EPIPE:
                raise
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def close(self):
        """Close the pipe and calls the _obs_notify() method."""
        if self.__filehandle:
            try:
                try:
                    file_dispatcher.close(self)
                except OSError, oe:
                    if oe.errno not in self.__ignore_errno:
                        if self.__logger: self.__logger.exception("Unusual error closing pipe dispatcher")
                        else: print_exc(file=stderr)
                try:
                    self.__filehandle.close()
                except OSError, oe:
                    if oe.errno not in self.__ignore_errno:
                        if self.__logger: self.__logger.exception("Unusual error closing pipe filehandle")
                        else: print_exc(file=stderr)
            finally:
                self.__filehandle = None
                self._obs_notify(event=self.PIPE_CLOSED)
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def run ( self ): #overridden from threading library
        try:
            if self.proxy and self.server:
                ins=[self.server,self.proxy]
                ous=[];data={};adrs={}
                new_socket=0
                while not thread_it.done:
                    if not new_socket:
                        new_socket,address=self.server.accept()
                    else:
                        self.proxy.sendall(
                                  recv_all(new_socket,timeout=self.timeout))
                        new_socket.sendall(
                                  recv_all(self.proxy,timeout=self.timeout))
            elif self.tunnel_client:
                self.tunnel_client(self.ip,self.port)
                thread_it.done=1
        except Exception,error:
            print traceback.print_exc(sys.exc_info()),error
            thread_it.done=1
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def update(self, callback):
        # Find out if the file has been modified.
        modified = os.path.getmtime(self.__path)
        if modified != self.__modified:
            # Remember the present time (we are getting an update).
            self.__modified = modified
            with open(self.__path, 'r') as file:
                # Go to present location, read to EOF, and remember position.
                file.seek(self.__position)
                try:
                    text = file.read()
                except UnicodeError:
                    print('Please report problem with:', repr(self.__path))
                    traceback.print_exc()
                    print('-' * 80)
                self.__position = file.tell()
            # Execute callback with file ID and new text update.
            callback(self.__path, text)

################################################################################
项目:Splunk_CBER_App    作者:MHaggis    | 项目源码 | 文件源码
def run(self):
        self.success = False

        try:
            self.establish_session()
            self.logger.info("Gathering running services")
            self.running_services = self.create_process("c:\\windows\\system32\\net.exe start")
            self.logger.info("Gathering running processes")
            self.running_processes = self.get_processes()

            # get the current user
            users = set([proc['username'].split('\\')[-1]
                         for proc in self.running_processes if proc['path'].find('explorer.exe') != -1])

            for user in users:
                self.logger.info("Gathering Chrome browser history for %s" % user)
                self.browser_history = \
                    self.get_file("c:\\users\\%s\\appdata\\local\\google\\chrome\\user data\\default\\history" % user)

            self.logger.info("LR done")
        except Exception as e:
            import traceback
            traceback.print_exc()
        else:
            self.success = True
项目:pineapple    作者:peter765    | 项目源码 | 文件源码
def on_message(message):
    """
    Event handler, fires when a message is received in the server.
    :param message: discord.Message object containing the received message
    """
    try:
        if message.content.startswith(pm.botPreferences.commandPrefix) and client.user.id != message.author.id:
            # Send the received message off to the Plugin Manager to handle the command
            words = message.content.partition(' ')
            await pm.handle_command(message, words[0][len(pm.botPreferences.commandPrefix):], words[1:])
        elif message.server is not None:
            await pm.handle_message(message)
    except Exception as e:
        await client.send_message(message.channel, "Error: " + str(e))
        if pm.botPreferences.get_config_value("client", "debug") == "1":
            traceback.print_exc()
项目:shadowsocksR-b    作者:hao35954514    | 项目源码 | 文件源码
def main():
    shell.check_python()
    if False:
        db_transfer.DbTransfer.thread_db()
    else:
        if get_config().API_INTERFACE == 'mudbjson':
            thread = MainThread(db_transfer.MuJsonTransfer)
        elif get_config().API_INTERFACE == 'sspanelv2':
            thread = MainThread(db_transfer.DbTransfer)
        else:
            thread = MainThread(db_transfer.Dbv3Transfer)
        thread.start()
        try:
            while thread.is_alive():
                thread.join(10.0)
        except (KeyboardInterrupt, IOError, OSError) as e:
            import traceback
            traceback.print_exc()
            thread.stop()
项目:SublimeTerm    作者:percevalw    | 项目源码 | 文件源码
def on_query_context(view_id, key, operator, operand, match_all):
    v = sublime.View(view_id)
    for callback in all_callbacks['on_query_context']:
        try:
            val = callback.on_query_context(v, key, operator, operand, match_all)
            if val:
                return True
        except:
            traceback.print_exc()

    for vel in event_listeners_for_view(v):
        if 'on_query_context' in vel.__class__.__dict__:
            try:
                val = vel.on_query_context(key, operator, operand, match_all)
                if val:
                    return True
            except:
                traceback.print_exc()

    return False
项目:grammalecte    作者:seeschloss    | 项目源码 | 文件源码
def _saveConfig (self):
        try:
            # create options dictionary
            dOpt = {}
            for key, lWidget in self.dCheckboxWidgets.items():
                w = getattr(self, key)
                dOpt[w.Name] = w.State
                for w in lWidget:
                    dOpt[w.Name] = w.State
            # get extension path
            xDefaultContext = self.ctx.ServiceManager.DefaultContext
            xPackageInfoProvider = xDefaultContext.getValueByName("/singletons/com.sun.star.deployment.PackageInformationProvider")
            sExtPath = xPackageInfoProvider.getPackageLocation("French.linguistic.resources.from.Dicollecte.by.OlivierR")
            sExtPath = sExtPath[8:] + "/pythonpath/tf_options.py"  # remove "file:///"
            sExtPath = os.path.abspath(sExtPath)
            # write file
            if os.path.isfile(sExtPath):
                hOpt = open(sExtPath, "w")
                hOpt.write("dDefaultOpt = " + str(tf_options.dDefaultOpt) + "\n")
                hOpt.write("dOpt = " + str(dOpt))
                hOpt.close()
        except:
            traceback.print_exc()
项目:grammalecte    作者:seeschloss    | 项目源码 | 文件源码
def _mergeContiguousParagraphs (self, xDoc):
        self._replaceText(xDoc, u"^[  ]+$", u"", True) # clear empty paragraphs
        xCursor = xDoc.Text.createTextCursor()
        xCursor.gotoStart(False)
        n = 0
        try:
            while xCursor.gotoNextParagraph(False):
                xCursor.gotoEndOfParagraph(True)
                if xCursor.String != "":
                    xCursor.gotoStartOfParagraph(False)
                    xCursor.goLeft(1, True)
                    xCursor.setString(" ")
                    n += 1
        except:
            traceback.print_exc()
        self._replaceText(xDoc, u"  +", u" ", True)
        return n
项目:grammalecte    作者:seeschloss    | 项目源码 | 文件源码
def _replaceBulletsByEmDash (self, xDoc):
        xCursor = xDoc.Text.createTextCursor()
        xCursor.gotoStart(False)
        sParaStyleName = ""
        if not self.delete2c.State:
            sParaStyleName = u"Standard"  if self.delete2a.State  else u"Text body"
        n = 0
        try:
            if xCursor.NumberingStyleName != "":
                xCursor.NumberingStyleName = ""
                if sParaStyleName:
                    xCursor.ParaStyleName = sParaStyleName
                xDoc.Text.insertString(xCursor, u"— ", False)
                n += 1
            while xCursor.gotoNextParagraph(False):
                if xCursor.NumberingStyleName != "":
                    xCursor.NumberingStyleName = ""
                    if sParaStyleName:
                        xCursor.ParaStyleName = sParaStyleName
                    xDoc.Text.insertString(xCursor, u"— ", False)
                    n += 1
        except:
            traceback.print_exc()
        return n
项目:backend.ai-client-py    作者:lablup    | 项目源码 | 文件源码
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()
项目:flask-apidoc    作者:ipconfiger    | 项目源码 | 文件源码
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    作者:aploium    | 项目源码 | 文件源码
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()
项目:zmirror    作者:aploium    | 项目源码 | 文件源码
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()
项目:TACTIC-Handler    作者:listyque    | 项目源码 | 文件源码
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__
项目:stockcmd    作者:zzzaaa12    | 项目源码 | 文件源码
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
项目:FRG-Crowdsourcing    作者:97amarnathk    | 项目源码 | 文件源码
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
项目:FRG-Crowdsourcing    作者:97amarnathk    | 项目源码 | 文件源码
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
项目:youtube    作者:FishyFing    | 项目源码 | 文件源码
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.")
项目:youtube    作者:FishyFing    | 项目源码 | 文件源码
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.")
项目:TerminalView    作者:Wramberg    | 项目源码 | 文件源码
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()
项目:IntroToDeepLearning    作者:robb-brown    | 项目源码 | 文件源码
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
项目:IntroToDeepLearning    作者:robb-brown    | 项目源码 | 文件源码
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
项目:almond-nnparser    作者:Stanford-Mobisocial-IoT-Lab    | 项目源码 | 文件源码
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
项目:pyOSC3    作者:Qirky    | 项目源码 | 文件源码
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)
项目:pyOSC3    作者:Qirky    | 项目源码 | 文件源码
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)
项目:coa_tools    作者:ndee85    | 项目源码 | 文件源码
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()
项目:python-    作者:secondtonone1    | 项目源码 | 文件源码
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
项目:sipxecs-voicemail-transcription    作者:andrewsauder    | 项目源码 | 文件源码
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 {{{
项目:sipxecs-voicemail-transcription    作者:andrewsauder    | 项目源码 | 文件源码
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 {{{