sys.exc_type

Here are the examples of the python api sys.exc_type taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

150 Examples 7

Example 1

Project: pyafipws
Source File: utils.py
View license
    def AnalizarXml(self, xml=""):
        "Analiza un mensaje XML (por defecto el ticket de acceso)"
        try:
            if not xml or xml=='XmlResponse':
                xml = self.XmlResponse 
            elif xml=='XmlRequest':
                xml = self.XmlRequest 
            self.xml = SimpleXMLElement(xml)
            return True
        except Exception, e:
            self.Excepcion = traceback.format_exception_only( sys.exc_type, sys.exc_value)[0]
            return False

Example 2

Project: pyafipws
Source File: utils.py
View license
    def ObtenerTagXml(self, *tags):
        "Busca en el Xml analizado y devuelve el tag solicitado"
        # convierto el xml a un objeto
        try:
            if self.xml:
                xml = self.xml
                # por cada tag, lo busco segun su nombre o posición
                for tag in tags:
                    xml = xml(tag) # atajo a getitem y getattr
                # vuelvo a convertir a string el objeto xml encontrado
                return str(xml)
        except Exception, e:
            self.Excepcion = traceback.format_exception_only( sys.exc_type, sys.exc_value)[0]

Example 3

Project: pyFosControl
Source File: camSniffer.py
View license
    def loop(self):
        """
        loop intended for console, press ^C to stop
        """
        try:
            while 1:
                self.p.dispatch(1, self.analyser.process_packet)
                if self.dumper:
                    self.p.dispatch(1, None)
        except KeyboardInterrupt:
            print('%s' % sys.exc_type)
            print('shutting down')
            print('%d packets received, %d packets dropped, %d packets dropped by interface' % self.p.stats())

Example 4

Project: RIDE
Source File: importer.py
View license
    def _import(self, name, fromlist=None, retry=True):
        try:
            try:
                return __import__(name, fromlist=fromlist)
            except ImportError:
                # Hack to support standalone Jython. For more information, see:
                # http://code.google.com/p/robotframework/issues/detail?id=515
                # http://bugs.jython.org/issue1778514
                if JYTHON and fromlist and retry:
                    __import__('%s.%s' % (name, fromlist[0]))
                    return self._import(name, fromlist, retry=False)
                # Cannot use plain raise due to
                # http://ironpython.codeplex.com/workitem/32332
                raise sys.exc_type, sys.exc_value, sys.exc_traceback
        except:
            raise DataError(*get_error_details())

Example 5

Project: pyfiscalprinter
Source File: controlador.py
View license
def inicializar_y_capturar_excepciones(func):
    "Decorador para inicializar y capturar errores"
    @wraps(func)
    def capturar_errores_wrapper(self, *args, **kwargs):
        try:
            # inicializo (limpio variables)
            self.Traceback = self.Excepcion = ""
            return func(self, *args, **kwargs)
        except Exception, e:
            ex = traceback.format_exception( sys.exc_type, sys.exc_value, sys.exc_traceback)
            self.Traceback = ''.join(ex)
            self.Excepcion = traceback.format_exception_only( sys.exc_type, sys.exc_value)[0]
            if self.LanzarExcepciones:
                raise
        finally:
            pass
    return capturar_errores_wrapper

Example 6

Project: tollgate
Source File: common.py
View license
	def process_exception(self, request, exception):
		if sys.exc_type is NotAConsoleException:
			return render_to_response(
				'frontend/not-a-console.html',
				context_instance=RequestContext(request)
			)
		else:
			return render_to_response(
				'frontend/error.html',
				{
					'error_message': _('An unhandled error occured.'),
					'excinfo': "%s: %s" % (sys.exc_type, sys.exc_value),
					'traceback': extract_tb(sys.exc_traceback)
				},
				context_instance=RequestContext(request)
			)

Example 7

Project: quickmapservices
Source File: settings_dialog.py
View license
    def get_contrib(self):
        QgsApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        try:
            ExtraSources().load_contrib_pack()
            QgsApplication.restoreOverrideCursor()
            info_message = self.tr('Last version of contrib pack was downloaded!')
            QMessageBox.information(self, PluginSettings.product_name(), info_message)

            self.dsManagerViewModel.resetModel()
        except:
            QgsApplication.restoreOverrideCursor()
            error_message = self.tr('Error on getting contrib pack: %s %s') % (sys.exc_type, sys.exc_value)
            QMessageBox.critical(self, PluginSettings.product_name(), error_message)

Example 8

Project: cgstudiomap
Source File: rpc.py
View license
    def execute(self, obj, method, *args):
        try:
            result = self.gateway.execute(obj, method, *args)
            return self.__convert(result)
        except Exception,e:
          import traceback,sys
          info = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))

Example 9

Project: tollgate
Source File: common.py
View license
	def process_exception(self, request, exception):
		if sys.exc_type is NotAConsoleException:
			return render_to_response(
				'frontend/not-a-console.html',
				context_instance=RequestContext(request)
			)
		else:
			return render_to_response(
				'frontend/error.html',
				{
					'error_message': _('An unhandled error occured.'),
					'excinfo': "%s: %s" % (sys.exc_type, sys.exc_value),
					'traceback': extract_tb(sys.exc_traceback)
				},
				context_instance=RequestContext(request)
			)

Example 10

Project: openerp-7.0
Source File: report_aeroo.py
View license
    def _raise_exception(self, e, print_id):
        tb_s = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
        self.logger(_("Report generation error!")+'\n'+tb_s, logging.ERROR)
        #subreports = self.oo_subreports.get(print_id, [])
        aeroo_print = self.active_prints.get(print_id, [])
        if aeroo_print:
            for sub_report in aeroo_print.subreports:
                if os.path.isfile(sub_report):
                    os.unlink(sub_report)
        raise Exception(_("Aeroo Reports: Error while generating the report."), e, str(e), _("For more reference inspect error logs."))

Example 11

Project: pytypedecl
Source File: parser.py
View license
def parse_string(string, name=None, filename=None, version=DEFAULT_VERSION):
  try:
    return TypeDeclParser(version).Parse(string, name, filename)
  except SyntaxError as unused_exception:
    # without all the tedious traceback stuff from PLY:
    # TODO: What happens if we don't catch SyntaxError?
    traceback.print_exception(sys.exc_type, sys.exc_value, None)
    sys.exit(1)

Example 12

Project: xraylarch
Source File: strutils.py
View license
def PrintExceptErr(err_str, print_trace=True):
    " print error on exceptions"
    print('\n***********************************')
    print(err_str)
    #print 'PrintExceptErr', err_str
    try:
        print('Error: %s' % sys.exc_type)
        etype, evalue, tback = sys.exc_info()
        if print_trace == False:
            tback = ''
        sys.excepthook(etype, evalue, tback)
    except:
        print('Error printing exception error!!')
        raise
    print('***********************************\n')

Example 13

Project: pyFosControl
Source File: camSniffer.py
View license
    def loop(self):
        """
        loop intended for console, press ^C to stop
        """
        try:
            while 1:
                self.p.dispatch(1, self.analyser.process_packet)
                if self.dumper:
                    self.p.dispatch(1, None)
        except KeyboardInterrupt:
            print('%s' % sys.exc_type)
            print('shutting down')
            print('%d packets received, %d packets dropped, %d packets dropped by interface' % self.p.stats())

Example 14

Project: cgstudiomap
Source File: rpc.py
View license
    def execute(self,obj, method, *args):
        sock = mysocket()
        try:
            sock.connect(self.host, self.port)
            data=(('object', 'execute',obj,method,)+args)
            sock.mysend(data)
            res=sock.myreceive()
            sock.disconnect()
            return res

        except Exception,e:
            import traceback,sys
            info = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))

Example 15

Project: typefacet
Source File: TTX.py
View license
	def mainloop(self, mask=FrameWork.everyEvent, wait=0):
		self.quitting = 0
		while not self.quitting:
			try:
				self.do1event(mask, wait)
			except self.__class__:
				# D'OH! FrameWork tries to quit us on cmd-.!
				pass
			except KeyboardInterrupt:
				pass
			except ttLib.xmlImport.xml_parse_error, why:
				EasyDialogs.Message(
					"An error occurred while parsing the XML file:\n" + why)
			except:
				exc = traceback.format_exception(sys.exc_type, sys.exc_value, None)[0]
				exc = string.strip(exc)
				EasyDialogs.Message("An error occurred!\n%s\n[see the logfile '%s' for details]" % 
						(exc, LOGFILENAME))
				traceback.print_exc()

Example 16

Project: quickmapservices
Source File: settings_dialog.py
View license
    def get_contrib(self):
        QgsApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        try:
            ExtraSources().load_contrib_pack()
            QgsApplication.restoreOverrideCursor()
            info_message = self.tr('Last version of contrib pack was downloaded!')
            QMessageBox.information(self, PluginSettings.product_name(), info_message)

            self.dsManagerViewModel.resetModel()
        except:
            QgsApplication.restoreOverrideCursor()
            error_message = self.tr('Error on getting contrib pack: %s %s') % (sys.exc_type, sys.exc_value)
            QMessageBox.critical(self, PluginSettings.product_name(), error_message)

Example 17

Project: LibrERP
Source File: report_aeroo.py
View license
    def _raise_exception(self, e, print_id):
        tb_s = reduce(lambda x, y: x + y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
        _logger.error(_("Report generation error!") + '\n' + tb_s)
        # subreports = self.oo_subreports.get(print_id, [])
        aeroo_print = self.active_prints.get(print_id, [])
        if aeroo_print:
            for sub_report in aeroo_print.subreports:
                if os.path.isfile(sub_report):
                    os.unlink(sub_report)
        raise Exception(_("Aeroo Reports: Error while generating the report."), e, str(e),
                        _("For more reference inspect error logs."))

Example 18

Project: cgstudiomap
Source File: rpc.py
View license
    def login(self, db, user, password):

        global rpc_url

        sock = xmlrpclib.ServerProxy(rpc_url + 'common')

        try:
            res = sock.login(db, user, password)
        except Exception, e:
            import traceback,sys
            info = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
            return -1

        return res

Example 19

Project: odoo
Source File: rpc.py
View license
    def execute(self,obj, method, *args):
        sock = mysocket()
        try:
            sock.connect(self.host, self.port)
            data=(('object', 'execute',obj,method,)+args)
            sock.mysend(data)
            res=sock.myreceive()
            sock.disconnect()
            return res

        except Exception,e:
            import traceback,sys
            info = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))

Example 20

Project: deploymentmanager-samples
Source File: common.py
View license
def FormatException(message):
  """Adds more information to the exception."""
  message = ('Exception Type: %s\n'
             'Details: %s\n'
             'Message: %s\n') % (sys.exc_type, traceback.format_exc(), message)
  return message

Example 21

Project: odoo
Source File: rpc.py
View license
    def login(self, db, user, password):

        global rpc_url

        sock = xmlrpclib.ServerProxy(rpc_url + 'common')

        try:
            res = sock.login(db, user, password)
        except Exception, e:
            import traceback,sys
            info = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
            return -1

        return res

Example 22

Project: odoo
Source File: rpc.py
View license
    def execute(self, obj, method, *args):
        try:
            result = self.gateway.execute(obj, method, *args)
            return self.__convert(result)
        except Exception,e:
          import traceback,sys
          info = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))

Example 23

View license
def copyFile(srcPath, dstPath):
		if os.path.isfile(srcPath):
			try:
				shutil.copy(srcPath, dstPath)
				shutil.copystat(srcPath, dstPath)
				os.chmod(dstPath, kPermissions)
			except IOError:
				print "Failed to copy file %s to %s." % (srcPath, dstPath)
				print traceback.format_exception_only(sys.exc_type, sys.exc_value)[-1]
				print "Quitting - not all files were copied."
				raise InstallError
			print "Copied %s\n    to %s\n" % (srcPath, dstPath)
		else:
			print "Failed to find src file '%s'." % (srcPath)

Example 24

Project: autotest
Source File: views.py
View license
def handler500(request):
    t = loader.get_template('500.html')
    trace = traceback.format_exc()
    context = Context({
        'type': sys.exc_type,
        'value': sys.exc_value,
        'traceback': cgi.escape(trace)
    })
    return HttpResponseServerError(t.render(context))

Example 25

Project: cgstudiomap
Source File: ConvertBracesToField.py
View license
    def setValue(self):

        desktop=getDesktop()
        doc = desktop.getCurrentComponent()
        docinfo=  doc.getDocumentInfo()
        count = 0
        regexes = [
            ['[a-zA-Z0-9_]+\.[a-zA-Z0-9_.]+',"Field"],
            ['\\[\\[ *repeatIn\\( *([a-zA-Z0-9_\.]+), *\'([a-zA-Z0-9_]+)\' *\\) *\\]\\]', "RepeatIn"],
            ['\\[\\[ *([a-zA-Z0-9_\.]+) *\\]\\]', "Field"]
            # ['\\[\\[ ([a-zA-Z0-9_]+\.[a-zA-Z1-9]) \\]\\]',"Field"],
            # ['\\[\\[ [a-zA-Z0-9_\.]+ and ([a-zA-Z0-9_\.]+) or .+? \\]\\]',"Field"],
            # ['\\[\\[ ([a-zA-Z0-9_\.]+) or .+? \\]\\]',"Field"],
            # ['\\[\\[ ([a-zA-Z0-9_\.]+) and .+? \\]\\]',"Field"],
            # ['\\[\\[ .+? or ([a-zA-Z0-9_\.]+) \\]\\]',"Field"],
            # ['\\[\\[ (.+?) and ([a-zA-Z0-9_\.]+) \\]\\]',"Field"],
            # ['\\[\\[ .+? % ([a-zA-Z0-9_\.]+) \\]\\]',"Field"]
        ]
        oFieldObject = []
        oRepeatInObjects = []
        saRepeatInList = []
        sHost = docinfo.getUserFieldValue(0)
        nCount = 0
        oParEnum = doc.getTextFields().createEnumeration()
        while oParEnum.hasMoreElements():
            oPar = oParEnum.nextElement()
            nCount += 1
        getList(oRepeatInObjects,sHost,nCount)
        for ro in oRepeatInObjects:
            if ro.find("(")<>-1:
                saRepeatInList.append( [ ro[:ro.find("(")], ro[ro.find("(")+1:ro.find(")")] ])
        try:
            oParEnum = doc.getTextFields().createEnumeration()
            while oParEnum.hasMoreElements():
                oPar = oParEnum.nextElement()
                if oPar.supportsService("com.sun.star.text.TextField.DropDown"):
                    for reg in regexes:
                        res=re.findall(reg[0],oPar.Items[1])
                        if len(res) <> 0:
                            if res[0][0] == "objects":
                                sTemp = docinfo.getUserFieldValue(3)
                                sTemp = "|-." + sTemp[sTemp.rfind(".")+1:] + ".-|"
                                oPar.Items=(sTemp.encode("utf-8"),oPar.Items[1].replace(' ',""))
                                oPar.update()
                            elif type(res[0]) <> type(u''):

                                sObject = self.getRes(self.sock, docinfo.getUserFieldValue(3), res[0][0][res[0][0].find(".")+1:].replace(".","/"))
                                r = self.sock.execute(database, uid, self.password, docinfo.getUserFieldValue(3) , 'fields_get')
                                sExpr="|-." + r[res[0][0][res[0][0].rfind(".")+1:]]["string"] + ".-|"
                                oPar.Items=(sExpr.encode("utf-8"),oPar.Items[1].replace(' ',""))
                                oPar.update()
                            else:

                                obj = None
                                for rl in saRepeatInList:
                                    if rl[0] == res[0][:res[0].find(".")]:
                                        obj=rl[1]
                                try:
                                    sObject = self.getRes(self.sock, obj, res[0][res[0].find(".")+1:].replace(".","/"))
                                    r = self.sock.execute(database, uid, self.password, sObject , 'read',[1])
                                except Exception,e:
                                    r = "TTT"
                                    self.logobj.log_write('ConvertBracesToField', LOG_ERROR, str(e))
                                if len(r) <> 0:
                                    if r <> "TTT":
                                        if len(res)>1:
                                            sExpr=""
                                            print res
                                            if reg[1] == 'Field':
                                                for ires in res:
                                                    try:
                                                        sExpr=r[0][ires[ires.rfind(".")+1:]]
                                                        break
                                                    except Exception,e:
                                                        import traceback,sys
                                                        info = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
                                                        self.logobj.log_write('ConvertBracesToField', LOG_ERROR,info)
                                                try:
                                                    oPar.Items=(sExpr.encode("utf-8") ,oPar.Items[1])
                                                    oPar.update()
                                                except:
                                                    oPar.Items=(str(sExpr) ,oPar.Items[1])
                                                    oPar.update()
                                                    import traceback,sys
                                                    info = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
                                                    self.logobj.log_write('ConvertBracesToField', LOG_ERROR, info)

                                        else:
                                            sExpr=r[0][res[0][res[0].rfind(".")+1:]]
                                            try:

                                                if sExpr:
                                                    oPar.Items=(sExpr.encode("utf-8") ,oPar.Items[1])
                                                    oPar.update()
                                                else:
                                                     oPar.Items=(u"/",oPar.Items[1])
                                                     oPar.update()
                                            except:
                                                oPar.Items=(str(sExpr) ,oPar.Items[1])
                                                oPar.update()
                                                import traceback,sys
                                                info = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
                                                self.logobj.log_write('ConvertBracesToField', LOG_ERROR,info)

                                    else:
                                        oPar.Items=(u""+r,oPar.Items[1])
                                        oPar.update()
                                else:
                                    oPar.Items=(u"TTT",oPar.Items[1])
                                    oPar.update()
        except:
            import traceback,sys
            info = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
            self.logobj.log_write('ConvertBraceToField', LOG_ERROR, info)

Example 26

Project: Camelot
Source File: batch_job.py
View license
    def add_exception_to_message( self, 
                                  exc_type = None, 
                                  exc_val = None, 
                                  exc_tb = None ):
        """If an exception occurs in a batch job, this method can be used to add
        the stack trace of an exception to the message.
        
        If no arguments are given, `sys.exc_traceback` is used.
        
        :param exc_type: type of the exception, such as in `sys.exc_type`
        :param exc_val: value of the exception, such as in `sys.exc_value`
        :param exc_tb: a traceback object, such as in `sys.exc_traceback`
        """
        import traceback, cStringIO
        sio = cStringIO.StringIO()
        traceback.print_exception( exc_type or sys.exc_type, 
                                   exc_val or sys.exc_value,
                                   exc_tb or sys.exc_traceback,
                                   None, 
                                   sio )
        traceback_print = sio.getvalue()
        sio.close()
        self.add_strings_to_message( [ unicode(exc_type or sys.exc_type) ], 
                                     color = 'red' )
        self.add_strings_to_message( traceback_print.split('\n'),
                                     color = 'grey' )

Example 27

Project: Camelot
Source File: batch_job.py
View license
    def add_exception_to_message( self, 
                                  exc_type = None, 
                                  exc_val = None, 
                                  exc_tb = None ):
        """If an exception occurs in a batch job, this method can be used to add
        the stack trace of an exception to the message.
        
        If no arguments are given, `sys.exc_traceback` is used.
        
        :param exc_type: type of the exception, such as in `sys.exc_type`
        :param exc_val: value of the exception, such as in `sys.exc_value`
        :param exc_tb: a traceback object, such as in `sys.exc_traceback`
        """
        import traceback, cStringIO
        sio = cStringIO.StringIO()
        traceback.print_exception( exc_type or sys.exc_type, 
                                   exc_val or sys.exc_value,
                                   exc_tb or sys.exc_traceback,
                                   None, 
                                   sio )
        traceback_print = sio.getvalue()
        sio.close()
        self.add_strings_to_message( [ unicode(exc_type or sys.exc_type) ], 
                                     color = 'red' )
        self.add_strings_to_message( traceback_print.split('\n'),
                                     color = 'grey' )

Example 28

Project: odoo
Source File: ConvertBracesToField.py
View license
    def setValue(self):

        desktop=getDesktop()
        doc = desktop.getCurrentComponent()
        docinfo=  doc.getDocumentInfo()
        count = 0
        regexes = [
            ['[a-zA-Z0-9_]+\.[a-zA-Z0-9_.]+',"Field"],
            ['\\[\\[ *repeatIn\\( *([a-zA-Z0-9_\.]+), *\'([a-zA-Z0-9_]+)\' *\\) *\\]\\]', "RepeatIn"],
            ['\\[\\[ *([a-zA-Z0-9_\.]+) *\\]\\]', "Field"]
            # ['\\[\\[ ([a-zA-Z0-9_]+\.[a-zA-Z1-9]) \\]\\]',"Field"],
            # ['\\[\\[ [a-zA-Z0-9_\.]+ and ([a-zA-Z0-9_\.]+) or .+? \\]\\]',"Field"],
            # ['\\[\\[ ([a-zA-Z0-9_\.]+) or .+? \\]\\]',"Field"],
            # ['\\[\\[ ([a-zA-Z0-9_\.]+) and .+? \\]\\]',"Field"],
            # ['\\[\\[ .+? or ([a-zA-Z0-9_\.]+) \\]\\]',"Field"],
            # ['\\[\\[ (.+?) and ([a-zA-Z0-9_\.]+) \\]\\]',"Field"],
            # ['\\[\\[ .+? % ([a-zA-Z0-9_\.]+) \\]\\]',"Field"]
        ]
        oFieldObject = []
        oRepeatInObjects = []
        saRepeatInList = []
        sHost = docinfo.getUserFieldValue(0)
        nCount = 0
        oParEnum = doc.getTextFields().createEnumeration()
        while oParEnum.hasMoreElements():
            oPar = oParEnum.nextElement()
            nCount += 1
        getList(oRepeatInObjects,sHost,nCount)
        for ro in oRepeatInObjects:
            if ro.find("(")<>-1:
                saRepeatInList.append( [ ro[:ro.find("(")], ro[ro.find("(")+1:ro.find(")")] ])
        try:
            oParEnum = doc.getTextFields().createEnumeration()
            while oParEnum.hasMoreElements():
                oPar = oParEnum.nextElement()
                if oPar.supportsService("com.sun.star.text.TextField.DropDown"):
                    for reg in regexes:
                        res=re.findall(reg[0],oPar.Items[1])
                        if len(res) <> 0:
                            if res[0][0] == "objects":
                                sTemp = docinfo.getUserFieldValue(3)
                                sTemp = "|-." + sTemp[sTemp.rfind(".")+1:] + ".-|"
                                oPar.Items=(sTemp.encode("utf-8"),oPar.Items[1].replace(' ',""))
                                oPar.update()
                            elif type(res[0]) <> type(u''):

                                sObject = self.getRes(self.sock, docinfo.getUserFieldValue(3), res[0][0][res[0][0].find(".")+1:].replace(".","/"))
                                r = self.sock.execute(database, uid, self.password, docinfo.getUserFieldValue(3) , 'fields_get')
                                sExpr="|-." + r[res[0][0][res[0][0].rfind(".")+1:]]["string"] + ".-|"
                                oPar.Items=(sExpr.encode("utf-8"),oPar.Items[1].replace(' ',""))
                                oPar.update()
                            else:

                                obj = None
                                for rl in saRepeatInList:
                                    if rl[0] == res[0][:res[0].find(".")]:
                                        obj=rl[1]
                                try:
                                    sObject = self.getRes(self.sock, obj, res[0][res[0].find(".")+1:].replace(".","/"))
                                    r = self.sock.execute(database, uid, self.password, sObject , 'read',[1])
                                except Exception,e:
                                    r = "TTT"
                                    self.logobj.log_write('ConvertBracesToField', LOG_ERROR, str(e))
                                if len(r) <> 0:
                                    if r <> "TTT":
                                        if len(res)>1:
                                            sExpr=""
                                            print res
                                            if reg[1] == 'Field':
                                                for ires in res:
                                                    try:
                                                        sExpr=r[0][ires[ires.rfind(".")+1:]]
                                                        break
                                                    except Exception,e:
                                                        import traceback,sys
                                                        info = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
                                                        self.logobj.log_write('ConvertBracesToField', LOG_ERROR,info)
                                                try:
                                                    oPar.Items=(sExpr.encode("utf-8") ,oPar.Items[1])
                                                    oPar.update()
                                                except:
                                                    oPar.Items=(str(sExpr) ,oPar.Items[1])
                                                    oPar.update()
                                                    import traceback,sys
                                                    info = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
                                                    self.logobj.log_write('ConvertBracesToField', LOG_ERROR, info)

                                        else:
                                            sExpr=r[0][res[0][res[0].rfind(".")+1:]]
                                            try:

                                                if sExpr:
                                                    oPar.Items=(sExpr.encode("utf-8") ,oPar.Items[1])
                                                    oPar.update()
                                                else:
                                                     oPar.Items=(u"/",oPar.Items[1])
                                                     oPar.update()
                                            except:
                                                oPar.Items=(str(sExpr) ,oPar.Items[1])
                                                oPar.update()
                                                import traceback,sys
                                                info = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
                                                self.logobj.log_write('ConvertBracesToField', LOG_ERROR,info)

                                    else:
                                        oPar.Items=(u""+r,oPar.Items[1])
                                        oPar.update()
                                else:
                                    oPar.Items=(u"TTT",oPar.Items[1])
                                    oPar.update()
        except:
            import traceback,sys
            info = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
            self.logobj.log_write('ConvertBraceToField', LOG_ERROR, info)

Example 29

Project: CMi
Source File: jython_compat.py
View license
    def formatExceptionTrace(e):
        newStr = "".join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
        return newStr

Example 30

View license
    def formatExceptionTrace(e):
        newStr = "".join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
        return newStr

Example 31

Project: CMi
Source File: jython_compat.py
View license
    def formatExceptionTrace(e):
        newStr = "".join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
        return newStr

Example 32

Project: subscription-manager
Source File: hwprobe.py
View license
    def get_network_interfaces(self):
        netinfdict = {}
        old_ipv4_metakeys = ['ipv4_address', 'ipv4_netmask', 'ipv4_broadcast']
        ipv4_metakeys = ['address', 'netmask', 'broadcast']
        ipv6_metakeys = ['address', 'netmask']
        try:
            interfaces_info = ethtool.get_interfaces_info(ethtool.get_devices())
            for info in interfaces_info:
                master = None
                mac_address = info.mac_address
                device = info.device
                # Omit mac addresses for sit and lo device types. See BZ838123
                # mac address are per interface, not per address
                if self._should_get_mac_address(device):
                    key = '.'.join(['net.interface', device, 'mac_address'])
                    netinfdict[key] = mac_address

                # all of our supported versions of python-ethtool support
                # get_ipv6_addresses
                for addr in info.get_ipv6_addresses():
                    # ethtool returns a different scope for "public" IPv6 addresses
                    # on different versions of RHEL.  EL5 is "global", while EL6 is
                    # "universe".  Make them consistent.
                    scope = addr.scope
                    if scope == 'universe':
                        scope = 'global'

                    # Collect a list of addresses See bz #874735
                    for mkey in ipv6_metakeys:
                        key = '.'.join(['net.interface', info.device, 'ipv6_%s' % (mkey), scope])
                        list_key = key + "_list"
                        # we could specify a default here... that could hide
                        # api breakage though and unit testing hw detect is... meh
                        attr = getattr(addr, mkey) or 'Unknown'
                        netinfdict[key] = attr
                        if not netinfdict.get(list_key, None):
                            netinfdict[list_key] = "" + str(attr)
                        else:
                            netinfdict[list_key] += ", " + str(attr)

                # However, old version of python-ethtool do not support
                # get_ipv4_address
                #
                # python-ethtool's api changed between rhel6.3 and rhel6.4
                # (0.6-1.el6 to 0.6-2.el6)
                # (without revving the upstream version... bad python-ethtool!)
                # note that 0.6-5.el5 (from rhel5.9) has the old api
                #
                # previously, we got the 'ipv4_address' from the etherinfo object
                # directly. In the new api, that isn't exposed, so we get the list
                # of addresses on the interface, and populate the info from there.
                #
                # That api change as to address bz #759150. The bug there was that
                # python-ethtool only showed one ip address per interface. To
                # accomdate the finer grained info, the api changed...
                #
                if hasattr(info, 'get_ipv4_addresses'):
                    for addr in info.get_ipv4_addresses():
                        for mkey in ipv4_metakeys:
                            # append 'ipv4_' to match the older interface and keeps facts
                            # consistent
                            key = '.'.join(['net.interface', info.device, 'ipv4_%s' % (mkey)])
                            info_key = key + '_list'
                            attr = getattr(addr, mkey) or 'Unknown'

                            netinfdict[key] = attr
                            if not netinfdict.get(info_key, None):
                                netinfdict[info_key] = "" + str(attr)
                            else:
                                netinfdict[info_key] += ", " + str(attr)

                # check to see if we are actually an ipv4 interface
                elif hasattr(info, 'ipv4_address'):
                    for mkey in old_ipv4_metakeys:
                        key = '.'.join(['net.interface', device, mkey])
                        attr = getattr(info, mkey) or 'Unknown'
                        netinfdict[key] = attr
                # otherwise we are ipv6 and we handled that already

                # bonded slave devices can have their hwaddr changed
                #
                # "master" here refers to the slave's master device.
                # If we find a master link, we are a  slave, and we need
                # to check the /proc/net/bonding info to see what the
                # "permanent" hw address are for this slave
                try:
                    master = os.readlink('/sys/class/net/%s/master' % info.device)
                #FIXME
                except Exception:
                    master = None

                if master:
                    master_interface = os.path.basename(master)
                    permanent_mac_addr = self._get_slave_hwaddr(master_interface, info.device)
                    key = '.'.join(['net.interface', info.device, "permanent_mac_address"])
                    netinfdict[key] = permanent_mac_addr

        except Exception:
            print _("Error reading network interface information:"), sys.exc_type
        self.allhw.update(netinfdict)
        return netinfdict

Example 33

Project: syndicate
Source File: multicall.py
View license
    def call(self, calls):
        # Some error codes, borrowed from xmlrpc-c.
        REQUEST_REFUSED_ERROR = -507

        results = []
        for call in calls:
            try:
                name = call['methodName']
                params = call['params']
                if name == 'system.multicall':
                    errmsg = "Recursive system.multicall forbidden"
                    raise xmlrpclib.Fault(REQUEST_REFUSED_ERROR, errmsg)
                result = [self.api.call(self.source, name, *params)]
            except xmlrpclib.Fault, fault:
                result = {'faultCode': fault.faultCode,
                          'faultString': fault.faultString}
            except:
                errmsg = "%s:%s" % (sys.exc_type, sys.exc_value)
                result = {'faultCode': 1, 'faultString': errmsg}
            results.append(result)
        return results

Example 34

Project: cgstudiomap
Source File: Change.py
View license
    def btnNext_clicked(self, oActionEvent):
        global url
        aVal=''
        #aVal= Fetature used
        try:
            url = self.protocol[self.win.getListBoxSelectedItem("lstProtocol")]+self.win.getEditText("txtHost")+":"+self.win.getEditText("txtPort")
            self.sock=RPCSession(url)
            desktop=getDesktop()
            doc = desktop.getCurrentComponent()
            docinfo=doc.getDocumentInfo()
            docinfo.setUserFieldValue(0,url)
            res=self.sock.listdb()
            self.win.endExecute()
            ServerParameter(aVal,url)
        except :
            import traceback,sys
            info = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
            self.logobj.log_write('ServerParameter', LOG_ERROR, info)
            ErrorDialog("Connection to server is fail. Please check your Server Parameter.", "", "Error!")
            self.win.endExecute()

Example 35

Project: tryton
Source File: common.py
View license
def send_bugtracker(title, msg):
    from tryton import rpc
    parent = get_toplevel_window()
    win = gtk.Dialog(_('Bug Tracker'), parent,
            gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
            (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                gtk.STOCK_OK, gtk.RESPONSE_OK))
    win.set_icon(TRYTON_ICON)
    win.set_default_response(gtk.RESPONSE_OK)

    hbox = gtk.HBox()
    image = gtk.Image()
    image.set_from_stock('tryton-dialog-information',
            gtk.ICON_SIZE_DIALOG)
    hbox.pack_start(image, False, False)

    table = gtk.Table(2, 2)
    table.set_col_spacings(3)
    table.set_row_spacings(3)
    table.set_border_width(1)
    label_user = gtk.Label(_('User:'))
    label_user.set_alignment(1.0, 0.5)
    table.attach(label_user, 0, 1, 0, 1, yoptions=False,
            xoptions=gtk.FILL)
    entry_user = gtk.Entry()
    entry_user.set_activates_default(True)
    table.attach(entry_user, 1, 2, 0, 1, yoptions=False,
            xoptions=gtk.FILL)
    label_password = gtk.Label(_('Password:'))
    label_password.set_alignment(1.0, 0.5)
    table.attach(label_password, 0, 1, 1, 2, yoptions=False,
            xoptions=gtk.FILL)
    entry_password = gtk.Entry()
    entry_password.set_activates_default(True)
    entry_password.set_visibility(False)
    table.attach(entry_password, 1, 2, 1, 2, yoptions=False,
            xoptions=gtk.FILL)
    hbox.pack_start(table)

    win.vbox.pack_start(hbox)
    win.show_all()
    if rpc._USERNAME:
        entry_user.set_text(rpc._USERNAME)
        entry_password.grab_focus()
    else:
        entry_user.grab_focus()

    response = win.run()
    parent.present()
    user = entry_user.get_text()
    password = entry_password.get_text()
    win.destroy()
    if response == gtk.RESPONSE_OK:
        try:
            msg = msg.encode('ascii', 'replace')
            protocol = 'http'
            if ssl or hasattr(socket, 'ssl'):
                protocol = 'https'
            quote = partial(urllib.quote, safe="!$&'()*+,;=:")
            server = xmlrpclib.Server(
                ('%s://%s:%[email protected]' + CONFIG['roundup.xmlrpc'])
                % (protocol, quote(user), quote(password)), allow_none=True)
            if hashlib:
                msg_md5 = hashlib.md5(msg + '\n' + title).hexdigest()
            else:
                msg_md5 = md5.new(msg + '\n' + title).hexdigest()
            if not title:
                title = '[no title]'
            issue_id = None
            msg_ids = server.filter('msg', None, {'summary': str(msg_md5)})
            for msg_id in msg_ids:
                summary = server.display(
                    'msg%s' % msg_id, 'summary')['summary']
                if summary == msg_md5:
                    issue_ids = server.filter(
                        'issue', None, {'messages': msg_id})
                    if issue_ids:
                        issue_id = issue_ids[0]
                        break
            if issue_id:
                # issue to same message already exists, add user to nosy-list
                server.set('issue' + str(issue_id), *['nosy=+' + user])
                message(
                    _('The same bug was already reported by another user.\n'
                        'To keep you informed your username is added '
                        'to the nosy-list of this issue') + '%s' % issue_id)
            else:
                # create a new issue for this error-message
                # first create message
                msg_id = server.create('msg', *['content=' + msg,
                    'author=' + user, 'summary=' + msg_md5])
                # second create issue with this message
                issue_id = server.create('issue', *['messages=' + str(msg_id),
                    'nosy=' + user, 'title=' + title, 'priority=bug'])
                message(_('Created new bug with ID ')
                    + 'issue%s' % issue_id)
            webbrowser.open(CONFIG['roundup.url'] + 'issue%s' % issue_id,
                new=2)
        except (socket.error, xmlrpclib.Fault), exception:
            if (isinstance(exception, xmlrpclib.Fault)
                    and 'roundup.cgi.exceptions.Unauthorised' in
                    exception.faultString):
                message(_('Connection error.\nBad username or password.'))
                return send_bugtracker(title, msg)
            tb_s = reduce(lambda x, y: x + y,
                    traceback.format_exception(sys.exc_type,
                        sys.exc_value, sys.exc_traceback))
            message(_('Exception:') + '\n' + tb_s, msg_type=gtk.MESSAGE_ERROR)

Example 36

Project: cgstudiomap
Source File: ConvertBracesToField.py
View license
    def getBraces(self, aReportSyntex=None):
        if aReportSyntex is None:
            aReportSyntex = []
        desktop=getDesktop()
        doc = desktop.getCurrentComponent()
        aSearchString=[]
        aReplaceString=[]
        aRes=[]

        try:
            regexes = [
                ['\\[\\[ *repeatIn\\( *([a-zA-Z0-9_\.]+), *\'([a-zA-Z0-9_]+)\' *\\) *\\]\\]', "RepeatIn"],
                ['\\[\\[ *([a-zA-Z0-9_\.]+) *\\]\\]', "Field"],
                ['\\[\\[ *.+? *\\]\\]', "Expression"]
            ]

            search = doc.createSearchDescriptor()
            search.SearchRegularExpression = True

            for reg in regexes:
                search.SearchString = reg[0]
                found = doc.findFirst( search )
                while found:
                    res=re.findall(reg[0],found.String)
                    print len(res)

                    if found.String not in [r[0] for r in aReportSyntex] and len(res) == 1 :
                        text=found.getText()
                        oInputList = doc.createInstance("com.sun.star.text.TextField.DropDown")
                        if reg[1]<>"Expression":
                            oInputList.Items=(u""+found.String,u""+found.String)
                        else:
                            oInputList.Items=(u"?",u""+found.String)
                        aReportSyntex.append([oInputList,reg[1]])
                        text.insertTextContent(found,oInputList,False)
                        found.String =""

                    else:
                        aRes.append([res,reg[1]])
                        found = doc.findNext(found.End, search)
            search = doc.createSearchDescriptor()
            search.SearchRegularExpression = False

            for res in aRes:
                for r in res[0]:
                    search.SearchString=r
                    found=doc.findFirst(search)
                    while found:

                        text=found.getText()

                        oInputList = doc.createInstance("com.sun.star.text.TextField.DropDown")
                        if res[1]<>"Expression":
                            oInputList.Items=(u""+found.String,u""+found.String)
                        else:
                            oInputList.Items=(u"?",u""+found.String)
                        aReportSyntex.append([oInputList,res[1]])
                        text.insertTextContent(found,oInputList,False)
                        found.String =""
                        found = doc.findNext(found.End, search)
        except:
            import traceback,sys
            info = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
            self.logobj.log_write('ConvertBraceToField', LOG_ERROR, info)

Example 37

Project: cgstudiomap
Source File: ExportToRML.py
View license
    def __init__(self, ctx):
        self.ctx     = ctx
        self.module  = "openerp_report"
        self.version = "0.1"
        LoginTest()
        if not loginstatus and __name__=="package":
            exit(1)

        desktop=getDesktop()
        doc = desktop.getCurrentComponent()
        docinfo=doc.getDocumentInfo()
        global url
        self.sock=RPCSession(url)

        # Read Data from sxw file
        tmpsxw = tempfile.mktemp('.'+"sxw")

        if not doc.hasLocation():
            mytype = Array(makePropertyValue("MediaType","application/vnd.sun.xml.writer"),)
            doc.storeAsURL("file://"+tmpsxw,mytype)
        data = read_data_from_file( get_absolute_file_path( doc.getURL()[7:] ) )
        file_type = doc.getURL()[7:].split(".")[-1]
        if docinfo.getUserFieldValue(2) == "":
            ErrorDialog("Please Save this file on server","Use Send To Server Option in Odoo Report Menu","Error")
            exit(1)
        filename = self.GetAFileName()
        if not filename:
            exit(1)
        global passwd
        self.password = passwd
        try:

            res = self.sock.execute(database, uid, self.password, 'ir.actions.report.xml', 'sxwtorml',base64.encodestring(data),file_type)
            if res['report_rml_content']:
                write_data_to_file(get_absolute_file_path(filename), res['report_rml_content'])
        except Exception,e:
            import traceback,sys
            info = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
            self.logobj.log_write('ExportToRML',LOG_ERROR, info)
            ErrorDialog("Cannot save the file to the hard drive.", "Exception: %s." % e, "Error" )

Example 38

Project: babble
Source File: SimpleXMLRPCServer.py
View license
    def _marshaled_dispatch(self, data, dispatch_method = None):
        """Dispatches an XML-RPC method from marshalled (XML) data.

        XML-RPC methods are dispatched from the marshalled (XML) data
        using the _dispatch method and the result is returned as
        marshalled data. For backwards compatibility, a dispatch
        function can be provided as an argument (see comment in
        SimpleXMLRPCRequestHandler.do_POST) but overriding the
        existing method through subclassing is the prefered means
        of changing method dispatch behavior.
        """

        try:
            params, method = xmlrpclib.loads(data)

            # generate response
            if dispatch_method is not None:
                response = dispatch_method(method, params)
            else:
                response = self._dispatch(method, params)
            # wrap response in a singleton tuple
            response = (response,)
            response = xmlrpclib.dumps(response, methodresponse=1,
                                       allow_none=self.allow_none, encoding=self.encoding)
        except Fault, fault:
            response = xmlrpclib.dumps(fault, allow_none=self.allow_none,
                                       encoding=self.encoding)
        except:
            # report exception back to server
            response = xmlrpclib.dumps(
                xmlrpclib.Fault(1, "%s:%s" % (sys.exc_type, sys.exc_value)),
                encoding=self.encoding, allow_none=self.allow_none,
                )

        return response

Example 39

Project: pelisalacarta
Source File: compat.py
View license
    def formatExceptionTrace(e):
        newStr = "".join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
        return newStr

Example 40

Project: cgstudiomap
Source File: Fields.py
View license
    def __init__(self, sVariable="", sFields="", sDisplayName="", bFromModify=False):
        LoginTest()
        if not loginstatus and __name__=="package":
            exit(1)
        self.logobj=Logger()
        self.win = DBModalDialog(60, 50, 200, 225, "Field Builder")

        self.win.addFixedText("lblVariable", 27, 12, 60, 15, "Variable :")
        self.win.addComboBox("cmbVariable", 180-120-2, 10, 130, 15,True, itemListenerProc=self.cmbVariable_selected)
        self.insVariable = self.win.getControl( "cmbVariable" )

        self.win.addFixedText("lblFields", 10, 32, 60, 15, "Variable Fields :")
        self.win.addComboListBox("lstFields", 180-120-2, 30, 130, 150, False,True,itemListenerProc=self.lstbox_selected)
        self.insField = self.win.getControl( "lstFields" )

        self.win.addFixedText("lblUName", 8, 187, 60, 15, "Displayed name :")
        self.win.addEdit("txtUName", 180-120-2, 185, 130, 15,)

        self.win.addButton('btnOK',-5 ,-5,45,15,'Ok' ,actionListenerProc = self.btnOk_clicked )
        self.win.addButton('btnCancel',-5 - 45 - 5 ,-5,45,15,'Cancel' ,actionListenerProc = self.btnCancel_clicked )

        global passwd
        self.password = passwd
        global url
        self.sock=RPCSession(url)

        self.sValue=None
        self.sObj=None
        self.aSectionList=[]
        self.sGDisplayName=sDisplayName
        self.aItemList=[]
        self.aComponentAdd=[]
        self.aObjectList=[]
        self.aListFields=[]
        self.aVariableList=[]
        EnumDocument(self.aItemList,self.aComponentAdd)
        desktop=getDesktop()
        doc =desktop.getCurrentComponent()
        docinfo=doc.getDocumentInfo()
        self.sMyHost= ""

        if not docinfo.getUserFieldValue(3) == "" and not docinfo.getUserFieldValue(0)=="":
            self.sMyHost = docinfo.getUserFieldValue(0)
            self.count = 0
            oParEnum = doc.getTextFields().createEnumeration()

            while oParEnum.hasMoreElements():
                oPar = oParEnum.nextElement()
                if oPar.supportsService("com.sun.star.text.TextField.DropDown"):
                    self.count += 1

            getList(self.aObjectList, self.sMyHost,self.count)
            cursor = doc.getCurrentController().getViewCursor()
            text = cursor.getText()
            tcur = text.createTextCursorByRange(cursor)

            self.aVariableList.extend( filter( lambda obj: obj[:obj.find("(")] == "Objects", self.aObjectList ) )

            for i in range(len(self.aItemList)):
                try:
                    anItem = self.aItemList[i][1]
                    component = self.aComponentAdd[i]

                    if component == "Document":
                        sLVal = anItem[anItem.find(",'") + 2:anItem.find("')")]
                        self.aVariableList.extend( filter( lambda obj: obj[:obj.find("(")] == sLVal, self.aObjectList ) )

                    if tcur.TextSection:
                        getRecersiveSection(tcur.TextSection,self.aSectionList)
                        if component in self.aSectionList:
                            sLVal = anItem[anItem.find(",'") + 2:anItem.find("')")]
                            self.aVariableList.extend( filter( lambda obj: obj[:obj.find("(")] == sLVal, self.aObjectList ) )

                    if tcur.TextTable:
                        if not component == "Document" and component[component.rfind(".")+1:] == tcur.TextTable.Name:
                            VariableScope(tcur, self.aVariableList, self.aObjectList, self.aComponentAdd, self.aItemList, component)
                except:
                    import traceback,sys
                    info = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
                    self.logobj.log_write('Fields', LOG_ERROR, info)

            self.bModify=bFromModify
            if self.bModify==True:
                sItem=""
                for anObject in self.aObjectList:
                    if anObject[:anObject.find("(")] == sVariable:
                        sItem = anObject
                        self.insVariable.setText(sItem)
                genTree(
                    sItem[sItem.find("(")+1:sItem.find(")")],
                    self.aListFields,
                    self.insField,
                    self.sMyHost,
                    2,
                    ending_excl=['one2many','many2one','many2many','reference'],
                    recur=['many2one']
                )
                self.sValue= self.win.getListBoxItem("lstFields",self.aListFields.index(sFields))
            for var in self.aVariableList:

                    self.model_ids =self.sock.execute(database, uid, self.password, 'ir.model' ,  'search', [('model','=',var[var.find("(")+1:var.find(")")])])
                    fields=['name','model']
                    self.model_res = self.sock.execute(database, uid, self.password, 'ir.model', 'read', self.model_ids,fields)
                    if self.model_res <> []:
                        self.insVariable.addItem(var[:var.find("(")+1] + self.model_res[0]['name'] + ")" ,self.insVariable.getItemCount())
                    else:
                        self.insVariable.addItem(var ,self.insVariable.getItemCount())

            self.win.doModalDialog("lstFields",self.sValue)
        else:
            ErrorDialog("Please insert user define field Field-1 or Field-4","Just go to File->Properties->User Define \nField-1 E.g. http://localhost:8069 \nOR \nField-4 E.g. account.invoice")
            self.win.endExecute()

Example 41

Project: cgstudiomap
Source File: Fields.py
View license
    def lstbox_selected(self, oItemEvent):
        try:

            desktop=getDesktop()
            doc =desktop.getCurrentComponent()
            docinfo=doc.getDocumentInfo()
            sItem= self.win.getComboBoxText("cmbVariable")
            for var in self.aVariableList:
                if var[:var.find("(")+1]==sItem[:sItem.find("(")+1]:
                    sItem = var
            sMain=self.aListFields[self.win.getListBoxSelectedItemPos("lstFields")]
            sObject=self.getRes(self.sock,sItem[sItem.find("(")+1:-1],sMain[1:])
            ids = self.sock.execute(database, uid, self.password, sObject ,  'search', [])
            res = self.sock.execute(database, uid, self.password, sObject , 'read',[ids[0]])
            self.win.setEditText("txtUName",res[0][sMain[sMain.rfind("/")+1:]])
        except:
            import traceback,sys
            info = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
            self.logobj.log_write('Fields', LOG_ERROR, info)
            self.win.setEditText("txtUName","TTT")
        if self.bModify:
            self.win.setEditText("txtUName",self.sGDisplayName)

Example 42

Project: pelisalacarta
Source File: compat.py
View license
    def formatExceptionTrace(e):
        newStr = "".join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
        return newStr

Example 43

Project: cgstudiomap
Source File: Fields.py
View license
    def cmbVariable_selected(self, oItemEvent):
        if self.count > 0 :
            try:
                desktop=getDesktop()
                doc =desktop.getCurrentComponent()
                docinfo=doc.getDocumentInfo()
                self.win.removeListBoxItems("lstFields", 0, self.win.getListBoxItemCount("lstFields"))
                self.aListFields=[]
                tempItem = self.win.getComboBoxText("cmbVariable")
                for var in self.aVariableList:
                    if var[:var.find("(")] == tempItem[:tempItem.find("(")]:
                        sItem=var

                genTree(
                    sItem[sItem.find("(")+1:sItem.find(")")],
                    self.aListFields,
                    self.insField,
                    self.sMyHost,
                    2,
                    ending_excl=['one2many','many2one','many2many','reference'],
                    recur=['many2one']
                )
            except:
                import traceback,sys
                info = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
                self.logobj.log_write('Fields', LOG_ERROR, info)

Example 44

Project: cgstudiomap
Source File: functions.py
View license
def genTree(object, aList, insField, host, level=3, ending=None, ending_excl=None, recur=None, root='', actualroot=""):
    if ending is None:
        ending = []
    if ending_excl is None:
        ending_excl = []
    if recur is None:
        recur = []
    try:
        global url
        sock=RPCSession(url)
        global passwd
        res = sock.execute(database, uid, passwd, object , 'fields_get')
        key = res.keys()
        key.sort()
        for k in key:
            if (not ending or res[k]['type'] in ending) and ((not ending_excl) or not (res[k]['type'] in ending_excl)):
                insField.addItem(root+'/'+res[k]["string"],len(aList))
                aList.append(actualroot+'/'+k)
            if (res[k]['type'] in recur) and (level>0):
                genTree(res[k]['relation'],aList,insField,host ,level-1, ending, ending_excl, recur,root+'/'+res[k]["string"],actualroot+'/'+k)
    except:
        obj=Logger()
        import traceback,sys
        info = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
        obj.log_write('Function', LOG_ERROR, info)

Example 45

Project: babble
Source File: SimpleXMLRPCServer.py
View license
    def system_multicall(self, call_list):
        """system.multicall([{'methodName': 'add', 'params': [2, 2]}, ...]) => \
[[4], ...]

        Allows the caller to package multiple XML-RPC calls into a single
        request.

        See http://www.xmlrpc.com/discuss/msgReader$1208
        """

        results = []
        for call in call_list:
            method_name = call['methodName']
            params = call['params']

            try:
                # XXX A marshalling error in any response will fail the entire
                # multicall. If someone cares they should fix this.
                results.append([self._dispatch(method_name, params)])
            except Fault, fault:
                results.append(
                    {'faultCode' : fault.faultCode,
                     'faultString' : fault.faultString}
                    )
            except:
                results.append(
                    {'faultCode' : 1,
                     'faultString' : "%s:%s" % (sys.exc_type, sys.exc_value)}
                    )
        return results

Example 46

Project: pelisalacarta
Source File: jython_compat.py
View license
    def formatExceptionTrace(e):
        newStr = "".join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
        return newStr

Example 47

Project: cgstudiomap
Source File: functions.py
View license
def getChildTable(oPar, aItemList, aComponentAdd, sTableName=""):
    sNames = oPar.getCellNames()
    bEmptyTableFlag=True
    for val in sNames:
        oCell = oPar.getCellByName(val)
        oCurEnum = oCell.createEnumeration()
        while oCurEnum.hasMoreElements():
            try:
                oCur = oCurEnum.nextElement()

                if oCur.supportsService("com.sun.star.text.TextTable"):
                    if sTableName=="":
                        getChildTable(oCur,aItemList,aComponentAdd,oPar.Name)
                    else:
                        getChildTable(oCur,aItemList,aComponentAdd,sTableName+"."+oPar.Name)
                else:
                    oSecEnum = oCur.createEnumeration()
                    while oSecEnum.hasMoreElements():
                        oSubSection = oSecEnum.nextElement()
                        if oSubSection.supportsService("com.sun.star.text.TextField"):
                            bEmptyTableFlag=False
                            sItem=oSubSection.TextField.Items[1]
                            if sItem[sItem.find("[[ ")+3:sItem.find("(")]=="repeatIn":
                                if aItemList.__contains__(oSubSection.TextField.Items)==False:
                                    aItemList.append(oSubSection.TextField.Items)
                                if sTableName=="":
                                    if  aComponentAdd.__contains__(oPar.Name)==False:
                                        aComponentAdd.append(oPar.Name)
                                else:
                                    if aComponentAdd.__contains__(sTableName+"."+oPar.Name)==False:
                                        aComponentAdd.append(sTableName+"."+oPar.Name)
            except:
                obj=Logger()
                import traceback,sys
                info = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
                obj.log_write('Function', LOG_ERROR, info)
    if bEmptyTableFlag==True:
        aItemList.append((u'',u''))
        if sTableName=="":
            if  aComponentAdd.__contains__(oPar.Name)==False:
                aComponentAdd.append(oPar.Name)
        else:
            if aComponentAdd.__contains__(sTableName+"."+oPar.Name)==False:
                aComponentAdd.append(sTableName+"."+oPar.Name)
    return 0

Example 48

Project: pelisalacarta
Source File: jython_compat.py
View license
    def formatExceptionTrace(e):
        newStr = "".join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
        return newStr

Example 49

Project: pyafipws
Source File: iibb.py
View license
    def ConsultarContribuyentes(self, fecha_desde, fecha_hasta, cuit_contribuyente):
        "Realiza la consulta remota a ARBA, estableciendo los resultados"
        self.limpiar()
        try:

            self.xml = SimpleXMLElement(XML_ENTRADA_BASE)
            self.xml.fechaDesde = fecha_desde
            self.xml.fechaHasta = fecha_hasta
            self.xml.contribuyentes.contribuyente.cuitContribuyente = cuit_contribuyente

            xml = self.xml.as_xml()
            self.CodigoHash = md5.md5(xml).hexdigest()
            nombre = "DFEServicioConsulta_%s.xml" % self.CodigoHash

            # guardo el xml en el archivo a enviar y luego lo re-abro:
            archivo = open(os.path.join(tempfile.gettempdir(), nombre), "w")
            archivo.write(xml)
            archivo.close()
            archivo = open(os.path.join(tempfile.gettempdir(), nombre), "r")

            if not self.testing:
                response = self.client(user=self.Usuario, password=self.Password,
                                   file=archivo)
            else:
                response = open(self.testing).read()
            self.XmlResponse = response
            self.xml = SimpleXMLElement(response)
            if 'tipoError' in self.xml:
                self.TipoError = str(self.xml.tipoError)
                self.CodigoError = str(self.xml.codigoError)
                self.MensajeError = str(self.xml.mensajeError).decode('latin1').encode("ascii", "replace")
            if 'numeroComprobante' in self.xml:
                self.NumeroComprobante = str(self.xml.numeroComprobante)
                self.CantidadContribuyentes = int(self.xml.cantidadContribuyentes)
                if 'contribuyentes' in self.xml:
                    for contrib in self.xml.contribuyente:
                        c = {
                            'CuitContribuytente': str(contrib.cuitContribuyente),
                            'AlicuotaPercepcion': str(contrib.alicuotaPercepcion),
                            'AlicuotaRetencion': str(contrib.alicuotaRetencion),
                            'GrupoPercepcion': str(contrib.grupoPercepcion),
                            'GrupoRetencion': str(contrib.grupoRetencion),
                            'Errores': [],
                            }
                        self.contribuyentes.append(c)
                    # establecer valores del primer contrib (sin eliminarlo)
                    self.LeerContribuyente(pop=False)
            return True
        except Exception, e:
                ex = traceback.format_exception( sys.exc_type, sys.exc_value, sys.exc_traceback)
                self.Traceback = ''.join(ex)
                try:
                    self.Excepcion = traceback.format_exception_only( sys.exc_type, sys.exc_value)[0]
                except:
                    self.Excepcion = u"<no disponible>"
                return False

Example 50

Project: scapy
Source File: UTscapy.py
View license
def run_campaign(test_campaign, get_interactive_session, verb=2):
    passed=failed=0
    if test_campaign.preexec:
        test_campaign.preexec_output = get_interactive_session(test_campaign.preexec.strip())[0]
    for testset in test_campaign:
        for t in testset:
            t.output,res = get_interactive_session(t.test.strip())
            the_res = False
            try:
                if res is None or res:
                    the_res= True
            except Exception,msg:
                t.output+="UTscapy: Error during result interpretation:\n"
                t.output+="".join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback,))
            if the_res:
                t.res = True
                res = "passed"
                passed += 1
            else:
                t.res = False
                res = "failed"
                failed += 1
            t.result = res
            if verb > 1:
                print >>sys.stderr,"%(result)6s %(crc)s %(name)s" % t
    test_campaign.passed = passed
    test_campaign.failed = failed
    if verb:
        print >>sys.stderr,"Campaign CRC=%(crc)s  SHA=%(sha)s" % test_campaign
        print >>sys.stderr,"PASSED=%i FAILED=%i" % (passed, failed)
    return failed