Python traceback.print_exc() Examples

The following are code examples for showing how to use traceback.print_exc(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: monasca-transform   Author: openstack   File: test_transform_service.py    (Apache License 2.0) View Source Project 7 votes vote down vote up
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 
Example 2
Project: core-framework   Author: RedhawkSDR   File: config.py    (license) View Source Project 7 votes vote down vote up
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() 
Example 3
Project: bitcoin-trading-system   Author: vinicius-ronconi   File: executor.py    (GNU General Public License v3.0) View Source Project 7 votes vote down vote up
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() 
Example 4
Project: coa_tools   Author: ndee85   File: __init__.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
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() 
Example 5
Project: facerecognition   Author: guoxiaolu   File: ftp_upload.py    (license) View Source Project 6 votes vote down vote up
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() 
Example 6
Project: core-framework   Author: RedhawkSDR   File: base.py    (license) View Source Project 6 votes vote down vote up
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 
Example 7
Project: human-rl   Author: gsastry   File: build_feature_files.py    (MIT License) View Source Project 6 votes vote down vote up
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 
Example 8
Project: vscode-azurecli   Author: Microsoft   File: tooling.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 9
Project: ComicSpider   Author: QuantumLiu   File: comic.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def get_pages(self):
        '''
        ??Phantomjs??????????????????url
        Get all pages' urls using selenium an phantomJS
        return:
            a list of tuple (page_num,page_url)
        '''
        r_slt=r'onchange="select_page\(\)">([\s\S]*?)</select>'
        r_p=r'<option value="(.*?)".*?>?(\d*?)?<'
        try:
            dcap = dict(DesiredCapabilities.PHANTOMJS)
            # ???????????????
            dcap["phantomjs.page.settings.loadImages"] = False
            driver = webdriver.PhantomJS(desired_capabilities=dcap)
            driver.get(self.chapter_url)
            text=driver.page_source
            st=re.findall(r_slt,text)[0]
            self.pages = [(int(p[-1]),p[0]) for p in re.findall(r_p,st)]
        except Exception:
            traceback.print_exc()
            self.pages = []
        except KeyboardInterrupt:
            raise KeyboardInterrupt
        finally:
            driver.quit()
            print('Got {l} pages in chapter {ch}'.format(l=len(self.pages),ch=self.chapter_title))
            return self.pages 
Example 10
Project: ComicSpider   Author: QuantumLiu   File: comic.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
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 
Example 11
Project: ComicSpider   Author: QuantumLiu   File: comic.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
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 
Example 12
Project: kinect-2-libras   Author: inessadl   File: atexit.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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] 
Example 13
Project: git-of-theseus   Author: erikbern   File: analyze.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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 
Example 14
Project: stackimpact-python   Author: stackimpact   File: error_reporter_test.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
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() 
Example 15
Project: dl4mt-multi   Author: nyu-dl   File: evaluate_models.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
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 
Example 16
Project: bap-ida-python   Author: BinaryAnalysisPlatform   File: run.py    (MIT License) View Source Project 6 votes vote down vote up
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") 
Example 17
Project: bitcoin-arbitrage   Author: ucfyao   File: brokercny.py    (license) View Source Project 6 votes vote down vote up
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 
Example 18
Project: bitcoin-arbitrage   Author: ucfyao   File: huobicny.py    (license) View Source Project 6 votes vote down vote up
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 
Example 19
Project: bitcoin-arbitrage   Author: ucfyao   File: helpers.py    (license) View Source Project 6 votes vote down vote up
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 
Example 20
Project: bitcoin-arbitrage   Author: ucfyao   File: emailer.py    (license) View Source Project 6 votes vote down vote up
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() 
Example 21
Project: Flask_Blog   Author: sugarguo   File: fcgi_base.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
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 
Example 22
Project: code   Author: ActiveState   File: recipe-576967.py    (MIT License) View Source Project 6 votes vote down vote up
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) 
Example 23
Project: code   Author: ActiveState   File: recipe-213238.py    (MIT License) View Source Project 6 votes vote down vote up
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 
Example 24
Project: code   Author: ActiveState   File: recipe-577638.py    (MIT License) View Source Project 6 votes vote down vote up
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)

################################################################################ 
Example 25
Project: Splunk_CBER_App   Author: MHaggis   File: cbaction.py    (license) View Source Project 6 votes vote down vote up
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 
Example 26
Project: pineapple   Author: peter765   File: bot.py    (MIT License) View Source Project 6 votes vote down vote up
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() 
Example 27
Project: shadowsocksR-b   Author: hao35954514   File: server.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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() 
Example 28
Project: SublimeTerm   Author: percevalw   File: sublime_plugin.py    (license) View Source Project 6 votes vote down vote up
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 
Example 29
Project: grammalecte   Author: seeschloss   File: TextFormatter.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
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() 
Example 30
Project: grammalecte   Author: seeschloss   File: TextFormatter.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
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 
Example 31
Project: grammalecte   Author: seeschloss   File: TextFormatter.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
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 
Example 32
Project: backend.ai-client-py   Author: lablup   File: proxy.py    (MIT License) View Source Project 6 votes vote down vote up
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() 
Example 33
Project: flask-apidoc   Author: ipconfiger   File: generator.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 34
Project: zmirror   Author: aploium   File: zmirror.py    (MIT License) View Source Project 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 35
Project: zmirror   Author: aploium   File: test_exception.py    (MIT License) View Source Project 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 36
Project: TACTIC-Handler   Author: listyque   File: global_functions.py    (Eclipse Public License 1.0) View Source Project 6 votes vote down vote up
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__ 
Example 37
Project: stockcmd   Author: zzzaaa12   File: taiwan_stock.py    (MIT License) View Source Project 6 votes vote down vote up
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 
Example 38
Project: FRG-Crowdsourcing   Author: 97amarnathk   File: rackspace.py    (GNU Affero General Public License v3.0) View Source Project 6 votes vote down vote up
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 
Example 39
Project: FRG-Crowdsourcing   Author: 97amarnathk   File: rackspace.py    (GNU Affero General Public License v3.0) View Source Project 6 votes vote down vote up
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 
Example 40
Project: youtube   Author: FishyFing   File: Owner.py    (MIT License) View Source Project 6 votes vote down vote up
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.") 
Example 41
Project: youtube   Author: FishyFing   File: Owner.py    (MIT License) View Source Project 6 votes vote down vote up
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.") 
Example 42
Project: TerminalView   Author: Wramberg   File: sublime_plugin.py    (MIT License) View Source Project 6 votes vote down vote up
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() 
Example 43
Project: IntroToDeepLearning   Author: robb-brown   File: input_data.py    (MIT License) View Source Project 5 votes vote down vote up
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 
Example 44
Project: IntroToDeepLearning   Author: robb-brown   File: input_data.py    (MIT License) View Source Project 5 votes vote down vote up
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 
Example 45
Project: almond-nnparser   Author: Stanford-Mobisocial-IoT-Lab   File: query_handler.py    (license) View Source Project 5 votes vote down vote up
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 
Example 46
Project: pyOSC3   Author: Qirky   File: OSC3.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 47
Project: pyOSC3   Author: Qirky   File: OSC2.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 48
Project: coa_tools   Author: ndee85   File: __init__.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
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() 
Example 49
Project: python-   Author: secondtonone1   File: _dummy_thread.py    (license) View Source Project 5 votes vote down vote up
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 
Example 50
Project: sipxecs-voicemail-transcription   Author: andrewsauder   File: libmilter.py    (MIT License) View Source Project 5 votes vote down vote up
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 {{{