Python sys.exc_info() Examples

The following are 30 code examples of sys.exc_info(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sys , or try the search function .
Example #1
Source File: lambda_handler.py    From aws-auto-remediate with GNU General Public License v3.0 8 votes vote down vote up
def get_settings(self):
        """Return the DynamoDB aws-auto-remediate-settings table in a Python dict format
        
        Returns:
            dict -- aws-auto-remediate-settings table
        """
        settings = {}
        try:
            for record in boto3.client("dynamodb").scan(
                TableName=os.environ["SETTINGSTABLE"]
            )["Items"]:
                record_json = dynamodb_json.loads(record, True)
                settings[record_json["key"]] = record_json["value"]
        except:
            self.logging.error(
                f"Could not read DynamoDB table '{os.environ['SETTINGSTABLE']}'."
            )
            self.logging.error(sys.exc_info()[1])

        return settings 
Example #2
Source File: versioneer.py    From aospy with Apache License 2.0 6 votes vote down vote up
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
                env=None):
    """Call the given command(s)."""
    assert isinstance(commands, list)
    p = None
    for c in commands:
        try:
            dispcmd = str([c] + args)
            # remember shell=False, so use git.cmd on windows, not just git
            p = subprocess.Popen([c] + args, cwd=cwd, env=env,
                                 stdout=subprocess.PIPE,
                                 stderr=(subprocess.PIPE if hide_stderr
                                         else None))
            break
        except EnvironmentError:
            e = sys.exc_info()[1]
            if e.errno == errno.ENOENT:
                continue
            if verbose:
                print("unable to run %s" % dispcmd)
                print(e)
            return None, None
    else:
        if verbose:
            print("unable to find command, tried %s" % (commands,))
        return None, None
    stdout = p.communicate()[0].strip()
    if sys.version_info[0] >= 3:
        stdout = stdout.decode()
    if p.returncode != 0:
        if verbose:
            print("unable to run %s (error)" % dispcmd)
            print("stdout was %s" % stdout)
        return None, p.returncode
    return stdout, p.returncode 
Example #3
Source File: servers.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _start_http_thread(self):
        """HTTP servers MUST be running in new threads, so that the
        main thread persists to receive KeyboardInterrupt's. If an
        exception is raised in the httpserver's thread then it's
        trapped here, and the bus (and therefore our httpserver)
        are shut down.
        """
        try:
            self.httpserver.start()
        except KeyboardInterrupt:
            self.bus.log('<Ctrl-C> hit: shutting down HTTP server')
            self.interrupt = sys.exc_info()[1]
            self.bus.exit()
        except SystemExit:
            self.bus.log('SystemExit raised: shutting down HTTP server')
            self.interrupt = sys.exc_info()[1]
            self.bus.exit()
            raise
        except Exception:
            self.interrupt = sys.exc_info()[1]
            self.bus.log('Error in HTTP server: shutting down',
                         traceback=True, level=40)
            self.bus.exit()
            raise 
Example #4
Source File: reprconf.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def as_dict(self, raw=False, vars=None):
        """Convert an INI file to a dictionary"""
        # Load INI file into a dict
        result = {}
        for section in self.sections():
            if section not in result:
                result[section] = {}
            for option in self.options(section):
                value = self.get(section, option, raw=raw, vars=vars)
                try:
                    value = unrepr(value)
                except Exception:
                    x = sys.exc_info()[1]
                    msg = ('Config error in section: %r, option: %r, '
                           'value: %r. Config values must be valid Python.' %
                           (section, option, value))
                    raise ValueError(msg, x.__class__.__name__, x.args)
                result[section][option] = value
        return result 
Example #5
Source File: _cprequest.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def respond(self, path_info):
        """Generate a response for the resource at self.path_info. (Core)"""
        try:
            try:
                try:
                    self._do_respond(path_info)
                except (cherrypy.HTTPRedirect, cherrypy.HTTPError):
                    inst = sys.exc_info()[1]
                    inst.set_response()
                    self.stage = 'before_finalize (HTTPError)'
                    self.hooks.run('before_finalize')
                    cherrypy.serving.response.finalize()
            finally:
                self.stage = 'on_end_resource'
                self.hooks.run('on_end_resource')
        except self.throws:
            raise
        except Exception:
            if self.throw_errors:
                raise
            self.handle_error() 
Example #6
Source File: test_http.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_garbage_in(self):
        # Connect without SSL regardless of server.scheme
        c = HTTPConnection('%s:%s' % (self.interface(), self.PORT))
        c._output(b'gjkgjklsgjklsgjkljklsg')
        c._send_output()
        response = c.response_class(c.sock, method='GET')
        try:
            response.begin()
            self.assertEqual(response.status, 400)
            self.assertEqual(response.fp.read(22),
                             b'Malformed Request-Line')
            c.close()
        except socket.error:
            e = sys.exc_info()[1]
            # "Connection reset by peer" is also acceptable.
            if e.errno != errno.ECONNRESET:
                raise 
Example #7
Source File: security_hub_rules.py    From aws-auto-remediate with GNU General Public License v3.0 6 votes vote down vote up
def mfa_enabled_for_iam_console_access(self, resource_id):
        """Deletes login profile for user with console access that doesn't have MFA enabled

        Arguments:
            resource_id {string} -- IAM User ID

        Returns:
            boolean -- True if remediation is successful
        """
        try:
            page_user = self.client_iam.get_paginator("list_users").paginate()
            for username in page_user.search(
                f"Users[?UserId == '{resource_id}'].UserName"
            ):
                self.client_iam.delete_login_profile(UserName=username)
                self.logging.info(f"Deleted login profile for IAM User '{username}'.")
                return True
        except:
            self.logging.error(
                f"Could not delete login profile for IAM User '{resource_id}'."
            )
            self.logging.error(sys.exc_info()[1])
            return False 
Example #8
Source File: security_hub_rules.py    From aws-auto-remediate with GNU General Public License v3.0 6 votes vote down vote up
def multi_region_cloud_trail_enabled(self, resource_id):
        """Enables multi region CloudTrail
        
        Arguments:
            resource_id {string} -- CloudTrail Name
        
        Returns:
            boolean -- True if remediation is successful
        """
        try:
            self.client_cloudtrail.update_trail(
                Name=resource_id, IsMultiRegionTrail=True
            )
            self.logging.info(
                f"Enabled multi region trail for CloudTrail '{resource_id}'."
            )
            return True
        except:
            self.logging.error(
                f"Could not enable multi region trail for CloudTrail '{resource_id}'."
            )
            self.logging.error(sys.exc_info()[1])
            return False 
Example #9
Source File: security_hub_rules.py    From aws-auto-remediate with GNU General Public License v3.0 6 votes vote down vote up
def s3_bucket_public_read_prohibited(self, resource_id):
        """Sets the S3 Bucket ACL to "private" to prevent the Bucket from being publicly read.
        
        Arguments:
            resource_id {string} -- S3 Bucket Name
        
        Returns:
            boolean -- True if remediation was successful
        """
        try:
            self.client_s3.put_bucket_acl(ACL="private", Bucket=resource_id)

            self.logging.info(f"ACL set to 'private' for S3 Bucket '{resource_id}'.")
            return True
        except:
            self.logging.error(
                f"Could not set ACL set to 'private' for S3 Bucket '{resource_id}'."
            )
            self.logging.error(sys.exc_info()[1])
            return False 
Example #10
Source File: security_hub_rules.py    From aws-auto-remediate with GNU General Public License v3.0 6 votes vote down vote up
def s3_bucket_public_write_prohibited(self, resource_id):
        """Sets the S3 Bucket ACL to "private" to prevent the Bucket from being publicly written to.
        
        Arguments:
            resource_id {string} -- S3 Bucket Name
        
        Returns:
            boolean -- True if remediation was successful
        """
        try:
            self.client_s3.put_bucket_acl(ACL="private", Bucket=resource_id)

            self.logging.info(f"ACL set to 'private' for S3 Bucket '{resource_id}'.")
            return True
        except:
            self.logging.error(
                f"Could not set ACL set to 'private' for S3 Bucket '{resource_id}'."
            )
            self.logging.error(sys.exc_info()[1])
            return False 
Example #11
Source File: lambda_handler.py    From aws-auto-remediate with GNU General Public License v3.0 6 votes vote down vote up
def receive_message(self, queue_url):
        """Retrieves 10 messeges from an SQS Queue
        
        Arguments:
            queue_url {string} -- SQS Queue URL
        
        Returns:
            dictionary -- Dictionary of SQS messeges
        """
        try:
            return self.client_sqs.receive_message(
                QueueUrl=queue_url,
                MessageAttributeNames=["try_count"],
                MaxNumberOfMessages=10,
            )
        except:
            self.logging.error(
                f"Could not retrieve Messages from SQS Queue URL '{queue_url}'."
            )
            self.logging.error(sys.exc_info()[1])
            return {} 
Example #12
Source File: lambda_handler.py    From aws-auto-remediate with GNU General Public License v3.0 6 votes vote down vote up
def get_current_stacks(self):
        """Retrieve a list of all CloudFormation Stacks currently deployed your AWS accont and region
        
        Returns:
            list -- List of currently deployed AWS Config Rules
        """
        try:
            resources = self.client_cloudformation.list_stacks().get("StackSummaries")
        except:
            self.logging.error(sys.exc_info()[1])
            return None

        existing_stacks = []
        for resource in resources:
            if resource.get("StackStatus") not in ("DELETE_COMPLETE"):
                existing_stacks.append(resource.get("StackName"))

        return existing_stacks 
Example #13
Source File: lambda_handler.py    From aws-auto-remediate with GNU General Public License v3.0 6 votes vote down vote up
def get_settings(self):
        """Return the DynamoDB aws-auto-remediate-settings table in a Python dict format
        
        Returns:
            dict -- aws-auto-remediate-settings table
        """
        settings = {}
        try:
            for record in self.client_dynamodb.scan(
                TableName=os.environ["SETTINGSTABLE"]
            )["Items"]:
                record_json = dynamodb_json.loads(record, True)

                if "key" in record_json and "value" in record_json:
                    settings[record_json.get("key")] = record_json.get("value")
        except:
            self.logging.error(
                f"Could not read DynamoDB table '{os.environ['SETTINGSTABLE']}'."
            )
            self.logging.error(sys.exc_info()[1])

        return settings 
Example #14
Source File: lex.py    From SublimeKSP with GNU General Public License v3.0 6 votes vote down vote up
def get_caller_module_dict(levels):
    try:
        raise RuntimeError
    except RuntimeError:
        e,b,t = sys.exc_info()
        f = t.tb_frame
        while levels > 0:
            f = f.f_back                   
            levels -= 1
        ldict = f.f_globals.copy()
        if f.f_globals != f.f_locals:
            ldict.update(f.f_locals)

        return ldict

# -----------------------------------------------------------------------------
# _funcs_to_names()
#
# Given a list of regular expression functions, this converts it to a list
# suitable for output to a table file
# ----------------------------------------------------------------------------- 
Example #15
Source File: yacc.py    From SublimeKSP with GNU General Public License v3.0 6 votes vote down vote up
def get_caller_module_dict(levels):
    try:
        raise RuntimeError
    except RuntimeError:
        e,b,t = sys.exc_info()
        f = t.tb_frame
        while levels > 0:
            f = f.f_back                   
            levels -= 1
        ldict = f.f_globals.copy()
        if f.f_globals != f.f_locals:
            ldict.update(f.f_locals)

        return ldict

# -----------------------------------------------------------------------------
# parse_grammar()
#
# This takes a raw grammar rule string and parses it into production data
# ----------------------------------------------------------------------------- 
Example #16
Source File: SampleIO.py    From Caffe-Python-Data-Layer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def extract_sample(img, image_mean=None, resize=-1):
    """Extract image content from image string or from file
    TAKE:
    input - either file content as string or numpy array
    image_mean - numpy array of image mean or a values of size (1,3)
    resize - to resize image, set resize > 0; otherwise, don't resize
    """
    try:
        # if input is a file name, then read image; otherwise decode_imgstr
        if type(img) is np.ndarray:
            img_data = img
        else:
            img_data = decode_imgstr(img)
        if type(resize) in [tuple, list]:
            # resize in two dimensions
            img_data = scipy.misc.imresize(img_data, (resize[0], resize[1]))
        elif resize > 0:
            img_data = scipy.misc.imresize(img_data, (resize, resize))
        img_data = img_data.astype(np.float32, copy=False)
        img_data = img_data[:, :, ::-1]
        # change channel for caffe:
        img_data = img_data.transpose(2, 0, 1)  # to CxHxW
        # substract_mean
        if image_mean is not None:
            img_data = substract_mean(img_data, image_mean)
        return img_data
    except:
        print sys.exc_info()[0], sys.exc_info()[1]
        return 
Example #17
Source File: listener.py    From incubator-spot with Apache License 2.0 5 votes vote down vote up
def main():
    '''
        Main entry point for Spark Streaming Listener functionality.
    '''
    try: streaming_listener(**parse_args().__dict__)
    except SystemExit: raise
    except:
        sys.excepthook(*sys.exc_info())
        sys.exit(1) 
Example #18
Source File: exception_trace.py    From clikit with MIT License 5 votes vote down vote up
def __init__(
        self, exception, solution_provider_repository=None
    ):  # type: (Exception, ...) -> None
        self._exception = exception
        self._solution_provider_repository = solution_provider_repository
        self._exc_info = sys.exc_info()
        self._higlighter = Highlighter()
        self._ignore = None 
Example #19
Source File: weakref.py    From aegea with Apache License 2.0 5 votes vote down vote up
def _exitfunc(cls):
        # At shutdown invoke finalizers for which atexit is true.
        # This is called once all other non-daemonic threads have been
        # joined.
        reenable_gc = False
        try:
            if cls._registry:
                import gc
                if gc.isenabled():
                    reenable_gc = True
                    gc.disable()
                pending = None
                while True:
                    if pending is None or finalize._dirty:
                        pending = cls._select_for_exit()
                        finalize._dirty = False
                    if not pending:
                        break
                    f = pending.pop()
                    try:
                        # gc is disabled, so (assuming no daemonic
                        # threads) the following is the only line in
                        # this function which might trigger creation
                        # of a new finalizer
                        f()
                    except Exception:
                        sys.excepthook(*sys.exc_info())
                    assert f not in cls._registry
        finally:
            # prevent any more finalizers from executing during shutdown
            finalize._shutdown = True
            if reenable_gc:
                gc.enable() 
Example #20
Source File: _version.py    From aospy with Apache License 2.0 5 votes vote down vote up
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
                env=None):
    """Call the given command(s)."""
    assert isinstance(commands, list)
    p = None
    for c in commands:
        try:
            dispcmd = str([c] + args)
            # remember shell=False, so use git.cmd on windows, not just git
            p = subprocess.Popen([c] + args, cwd=cwd, env=env,
                                 stdout=subprocess.PIPE,
                                 stderr=(subprocess.PIPE if hide_stderr
                                         else None))
            break
        except EnvironmentError:
            e = sys.exc_info()[1]
            if e.errno == errno.ENOENT:
                continue
            if verbose:
                print("unable to run %s" % dispcmd)
                print(e)
            return None, None
    else:
        if verbose:
            print("unable to find command, tried %s" % (commands,))
        return None, None
    stdout = p.communicate()[0].strip()
    if sys.version_info[0] >= 3:
        stdout = stdout.decode()
    if p.returncode != 0:
        if verbose:
            print("unable to run %s (error)" % dispcmd)
            print("stdout was %s" % stdout)
        return None, p.returncode
    return stdout, p.returncode 
Example #21
Source File: versioneer.py    From xrft with MIT License 5 votes vote down vote up
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
                env=None):
    """Call the given command(s)."""
    assert isinstance(commands, list)
    p = None
    for c in commands:
        try:
            dispcmd = str([c] + args)
            # remember shell=False, so use git.cmd on windows, not just git
            p = subprocess.Popen([c] + args, cwd=cwd, env=env,
                                 stdout=subprocess.PIPE,
                                 stderr=(subprocess.PIPE if hide_stderr
                                         else None))
            break
        except EnvironmentError:
            e = sys.exc_info()[1]
            if e.errno == errno.ENOENT:
                continue
            if verbose:
                print("unable to run %s" % dispcmd)
                print(e)
            return None, None
    else:
        if verbose:
            print("unable to find command, tried %s" % (commands,))
        return None, None
    stdout = p.communicate()[0].strip()
    if sys.version_info[0] >= 3:
        stdout = stdout.decode()
    if p.returncode != 0:
        if verbose:
            print("unable to run %s (error)" % dispcmd)
            print("stdout was %s" % stdout)
        return None, p.returncode
    return stdout, p.returncode 
Example #22
Source File: _version.py    From xrft with MIT License 5 votes vote down vote up
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
                env=None):
    """Call the given command(s)."""
    assert isinstance(commands, list)
    p = None
    for c in commands:
        try:
            dispcmd = str([c] + args)
            # remember shell=False, so use git.cmd on windows, not just git
            p = subprocess.Popen([c] + args, cwd=cwd, env=env,
                                 stdout=subprocess.PIPE,
                                 stderr=(subprocess.PIPE if hide_stderr
                                         else None))
            break
        except EnvironmentError:
            e = sys.exc_info()[1]
            if e.errno == errno.ENOENT:
                continue
            if verbose:
                print("unable to run %s" % dispcmd)
                print(e)
            return None, None
    else:
        if verbose:
            print("unable to find command, tried %s" % (commands,))
        return None, None
    stdout = p.communicate()[0].strip()
    if sys.version_info[0] >= 3:
        stdout = stdout.decode()
    if p.returncode != 0:
        if verbose:
            print("unable to run %s (error)" % dispcmd)
            print("stdout was %s" % stdout)
        return None, p.returncode
    return stdout, p.returncode 
Example #23
Source File: _cperror.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, status=500, message=None):
        self.status = status
        try:
            self.code, self.reason, defaultmsg = _httputil.valid_status(status)
        except ValueError:
            raise self.__class__(500, _exc_info()[1].args[0])

        if self.code < 400 or self.code > 599:
            raise ValueError('status must be between 400 and 599.')

        # See http://www.python.org/dev/peps/pep-0352/
        # self.message = message
        self._message = message or defaultmsg
        CherryPyException.__init__(self, status, message) 
Example #24
Source File: _cperror.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def format_exc(exc=None):
    """Return exc (or sys.exc_info if None), formatted."""
    try:
        if exc is None:
            exc = _exc_info()
        if exc == (None, None, None):
            return ''
        import traceback
        return ''.join(traceback.format_exception(*exc))
    finally:
        del exc 
Example #25
Source File: _cpwsgi.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __call__(self, environ, start_response):
        redirections = []
        while True:
            environ = environ.copy()
            try:
                return self.nextapp(environ, start_response)
            except _cherrypy.InternalRedirect:
                ir = _sys.exc_info()[1]
                sn = environ.get('SCRIPT_NAME', '')
                path = environ.get('PATH_INFO', '')
                qs = environ.get('QUERY_STRING', '')

                # Add the *previous* path_info + qs to redirections.
                old_uri = sn + path
                if qs:
                    old_uri += '?' + qs
                redirections.append(old_uri)

                if not self.recursive:
                    # Check to see if the new URI has been redirected to
                    # already
                    new_uri = sn + ir.path
                    if ir.query_string:
                        new_uri += '?' + ir.query_string
                    if new_uri in redirections:
                        ir.request.close()
                        tmpl = (
                            'InternalRedirector visited the same URL twice: %r'
                        )
                        raise RuntimeError(tmpl % new_uri)

                # Munge the environment and try again.
                environ['REQUEST_METHOD'] = 'GET'
                environ['PATH_INFO'] = ir.path
                environ['QUERY_STRING'] = ir.query_string
                environ['wsgi.input'] = io.BytesIO()
                environ['CONTENT_LENGTH'] = '0'
                environ['cherrypy.previous_request'] = ir.request 
Example #26
Source File: _cpdispatch.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __call__(self):
        try:
            return self.callable(*self.args, **self.kwargs)
        except TypeError:
            x = sys.exc_info()[1]
            try:
                test_callable_spec(self.callable, self.args, self.kwargs)
            except cherrypy.HTTPError:
                raise sys.exc_info()[1]
            except Exception:
                raise x
            raise 
Example #27
Source File: wspbus.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def publish(self, channel, *args, **kwargs):
        """Return output of all subscribers for the given channel."""
        if channel not in self.listeners:
            return []

        exc = ChannelFailures()
        output = []

        raw_items = (
            (self._priorities[(channel, listener)], listener)
            for listener in self.listeners[channel]
        )
        items = sorted(raw_items, key=operator.itemgetter(0))
        for priority, listener in items:
            try:
                output.append(listener(*args, **kwargs))
            except KeyboardInterrupt:
                raise
            except SystemExit:
                e = sys.exc_info()[1]
                # If we have previous errors ensure the exit code is non-zero
                if exc and e.code == 0:
                    e.code = 1
                raise
            except Exception:
                exc.handle_exception()
                if channel == 'log':
                    # Assume any further messages to 'log' will fail.
                    pass
                else:
                    self.log('Error in %r listener %r' % (channel, listener),
                             level=40, traceback=True)
        if exc:
            raise exc
        return output 
Example #28
Source File: wspbus.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def start(self):
        """Start all services."""
        atexit.register(self._clean_exit)

        self.state = states.STARTING
        self.log('Bus STARTING')
        try:
            self.publish('start')
            self.state = states.STARTED
            self.log('Bus STARTED')
        except (KeyboardInterrupt, SystemExit):
            raise
        except Exception:
            self.log('Shutting down due to error in start listener:',
                     level=40, traceback=True)
            e_info = sys.exc_info()[1]
            try:
                self.exit()
            except Exception:
                # Any stop/exit errors will be logged inside publish().
                pass
            # Re-raise the original error
            raise e_info 
Example #29
Source File: wspbus.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def log(self, msg='', level=20, traceback=False):
        """Log the given message. Append the last traceback if requested."""
        if traceback:
            msg += '\n' + ''.join(_traceback.format_exception(*sys.exc_info()))
        self.publish('log', msg, level) 
Example #30
Source File: _cpreqbody.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def finish(self):
        self.done = True
        if self.has_trailers and hasattr(self.fp, 'read_trailer_lines'):
            self.trailers = {}

            try:
                for line in self.fp.read_trailer_lines():
                    if line[0] in b' \t':
                        # It's a continuation line.
                        v = line.strip()
                    else:
                        try:
                            k, v = line.split(b':', 1)
                        except ValueError:
                            raise ValueError('Illegal header line.')
                        k = k.strip().title()
                        v = v.strip()

                    if k in cheroot.server.comma_separated_headers:
                        existing = self.trailers.get(k)
                        if existing:
                            v = b', '.join((existing, v))
                    self.trailers[k] = v
            except Exception:
                e = sys.exc_info()[1]
                if e.__class__.__name__ == 'MaxSizeExceeded':
                    # Post data is too big
                    raise cherrypy.HTTPError(
                        413, 'Maximum request length: %r' % e.args[1])
                else:
                    raise