Python sys.exc_info() Examples

The following are 60 code examples for showing how to use sys.exc_info(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

You may also check out all available functions/classes of the module sys , or try the search function .

Example 1
Project: cherrypy   Author: cherrypy   File: wspbus.py    License: BSD 3-Clause "New" or "Revised" License 6 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 2
Project: cherrypy   Author: cherrypy   File: servers.py    License: 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 3
Project: cherrypy   Author: cherrypy   File: reprconf.py    License: 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 4
Project: cherrypy   Author: cherrypy   File: _cprequest.py    License: 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 5
Project: cherrypy   Author: cherrypy   File: test_http.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_http_over_https(self):
        if self.scheme != 'https':
            return self.skip('skipped (not running HTTPS)... ')

        # Try connecting without SSL.
        conn = HTTPConnection('%s:%s' % (self.interface(), self.PORT))
        conn.putrequest('GET', '/', skip_host=True)
        conn.putheader('Host', self.HOST)
        conn.endheaders()
        response = conn.response_class(conn.sock, method='GET')
        try:
            response.begin()
            self.assertEqual(response.status, 400)
            self.body = response.read()
            self.assertBody('The client sent a plain HTTP request, but this '
                            'server only speaks HTTPS on this port.')
        except socket.error:
            e = sys.exc_info()[1]
            # "Connection reset by peer" is also acceptable.
            if e.errno != errno.ECONNRESET:
                raise 
Example 6
Project: cherrypy   Author: cherrypy   File: test_http.py    License: 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
Project: aws-auto-remediate   Author: servian   File: security_hub_rules.py    License: 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
Project: aws-auto-remediate   Author: servian   File: security_hub_rules.py    License: 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
Project: aws-auto-remediate   Author: servian   File: security_hub_rules.py    License: 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
Project: aws-auto-remediate   Author: servian   File: security_hub_rules.py    License: 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
Project: aws-auto-remediate   Author: servian   File: lambda_handler.py    License: 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 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 12
Project: aws-auto-remediate   Author: servian   File: lambda_handler.py    License: 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 13
Project: aws-auto-remediate   Author: servian   File: lambda_handler.py    License: 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 14
Project: aws-auto-remediate   Author: servian   File: lambda_handler.py    License: 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 15
Project: SublimeKSP   Author: nojanath   File: lex.py    License: 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 16
Project: SublimeKSP   Author: nojanath   File: yacc.py    License: 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 17
Project: Caffe-Python-Data-Layer   Author: liuxianming   File: SampleIO.py    License: 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 18
Project: incubator-spot   Author: apache   File: listener.py    License: 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 19
Project: clikit   Author: sdispater   File: exception_trace.py    License: 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 20
Project: aegea   Author: kislyuk   File: weakref.py    License: 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 21
Project: aospy   Author: spencerahill   File: versioneer.py    License: 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 22
Project: aospy   Author: spencerahill   File: _version.py    License: 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 23
Project: xrft   Author: xgcm   File: versioneer.py    License: 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 24
Project: xrft   Author: xgcm   File: _version.py    License: 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 25
Project: cherrypy   Author: cherrypy   File: _cperror.py    License: 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 26
Project: cherrypy   Author: cherrypy   File: _cperror.py    License: 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 27
Project: cherrypy   Author: cherrypy   File: _cpwsgi.py    License: 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 28
Project: cherrypy   Author: cherrypy   File: _cpdispatch.py    License: 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 29
Project: cherrypy   Author: cherrypy   File: wspbus.py    License: 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 30
Project: cherrypy   Author: cherrypy   File: wspbus.py    License: 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 31
Project: cherrypy   Author: cherrypy   File: _cpreqbody.py    License: 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 
Example 32
Project: cherrypy   Author: cherrypy   File: xmlrpcutil.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def on_error(*args, **kwargs):
    """Construct HTTP response body for an error response."""
    body = str(sys.exc_info()[1])
    _set_response(xmlrpc_dumps(XMLRPCFault(1, body))) 
Example 33
Project: cherrypy   Author: cherrypy   File: _cprequest.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def handle_error(self):
        """Handle the last unanticipated exception. (Core)"""
        try:
            self.hooks.run('before_error_response')
            if self.error_response:
                self.error_response()
            self.hooks.run('after_error_response')
            cherrypy.serving.response.finalize()
        except cherrypy.HTTPRedirect:
            inst = sys.exc_info()[1]
            inst.set_response()
            cherrypy.serving.response.finalize() 
Example 34
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: exceptionHandling.py    License: MIT License 5 votes vote down vote up
def run(self):
    try:
      raise Exception("This broke stuff")
    except:
      except_type, except_class, tb = sys.exc_info()

      self.pipein = os.fdopen(self.pipein, 'w')
      self.pipein.write(str(tb))
      self.pipein.close() 
Example 35
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: threadException.py    License: MIT License 5 votes vote down vote up
def myThread(queue):
  while True:
    try:
      time.sleep(2)
      raise Exception("Exception Thrown In Child Thread {}".format(threading.current_thread()))
    except:
      queue.put(sys.exc_info()) 
Example 36
Project: disentangling_conditional_gans   Author: zalandoresearch   File: dataset_tool.py    License: MIT License 5 votes vote down vote up
def __init__(self):
        self.value = sys.exc_info()[1]
        self.traceback = traceback.format_exc()

#---------------------------------------------------------------------------- 
Example 37
Project: disentangling_conditional_gans   Author: zalandoresearch   File: dataset_tool.py    License: MIT License 5 votes vote down vote up
def create_lsun(tfrecord_dir, lmdb_dir, resolution=256, max_images=None):
    print('Loading LSUN dataset from "%s"' % lmdb_dir)
    import lmdb # pip install lmdb
    import cv2 # pip install opencv-python
    import io
    with lmdb.open(lmdb_dir, readonly=True).begin(write=False) as txn:
        total_images = txn.stat()['entries']
        if max_images is None:
            max_images = total_images
        with TFRecordExporter(tfrecord_dir, max_images) as tfr:
            for idx, (key, value) in enumerate(txn.cursor()):
                try:
                    try:
                        img = cv2.imdecode(np.fromstring(value, dtype=np.uint8), 1)
                        if img is None:
                            raise IOError('cv2.imdecode failed')
                        img = img[:, :, ::-1] # BGR => RGB
                    except IOError:
                        img = np.asarray(PIL.Image.open(io.BytesIO(value)))
                    crop = np.min(img.shape[:2])
                    img = img[(img.shape[0] - crop) // 2 : (img.shape[0] + crop) // 2, (img.shape[1] - crop) // 2 : (img.shape[1] + crop) // 2]
                    img = PIL.Image.fromarray(img, 'RGB')
                    img = img.resize((resolution, resolution), PIL.Image.ANTIALIAS)
                    img = np.asarray(img)
                    img = img.transpose(2, 0, 1) # HWC => CHW
                    tfr.add_image(img)
                except:
                    print(sys.exc_info()[1])
                if tfr.cur_images == max_images:
                    break
        
#---------------------------------------------------------------------------- 
Example 38
Project: L.E.S.M.A   Author: NatanaelAntonioli   File: L.E.S.M.A. - Fabrica de Noobs Speedtest.py    License: Apache License 2.0 5 votes vote down vote up
def get_exception():
	"""Helper function to work with py2.4-py3 for getting the current
	exception in a try/except block
	"""
	return sys.exc_info()[1] 
Example 39
Project: multibootusb   Author: mbusb   File: isodump3.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, isofile):
        try:
            f = open(isofile, 'rb')
        except(IOError):
            sys.stderr.write("can't open {0}".format(isofile))
            raise

        if os.path.getsize(isofile) == 0:
            raise IOError("File {0} appears to be empty".format(isofile))

        self.isoFile = f
        self.priVol = None
        self.rootDir = None
        self.rripOffset = -1

        desc_nr = 0
        while True:
            desc_nr = desc_nr + 1
            try:
                self.isoFile.seek(BLOCK_SIZE*(15+desc_nr))
                volume_dsc = self.isoFile.read(BLOCK_SIZE)
                flag = struct.unpack('B',volume_dsc[0:1])[0]
                if flag == 1:
                    self.__readPrimaryVolume__(volume_dsc)
                    continue
                if flag == 255:
                    break
            except Exception as e:
                gen.log("Got exception when init iso file:", sys.exc_info()[0])
                self.priVol = None
                self.rootDir = None
                break 
Example 40
Project: aws-auto-remediate   Author: servian   File: config_rules.py    License: GNU General Public License v3.0 5 votes vote down vote up
def rds_instance_public_access_check(self, resource_id):
        """Sets Publicly Accessible option to False for public RDS Instances
        
        Arguments:
            resource_id {DbiResourceId} -- The AWS Region-unique, immutable identifier for the DB instance
        
        Returns:
            boolean -- True if remediation was successful
        """
        try:
            paginator = self.client_rds.get_paginator("describe_db_instances")
            response = paginator.paginate(DBInstanceIdentifier=resource_id)
        except:
            self.logging.error("Could not describe RDS DB Instances.")
            return False
        else:
            for instance in response["DBInstances"]:
                try:
                    self.client_rds.modify_db_instance(
                        DBInstanceIdentifier=instance["DBInstanceIdentifier"],
                        PubliclyAccessible=False,
                    )
                    self.logging.info(
                        f"Disabled Public Accessibility for RDS Instance '{resource_id}'."
                    )
                    return True
                except:
                    self.logging.error(
                        f"Could not disable Public Accessibility for RDS Instance '{resource_id}'."
                    )
                    self.logging.error(sys.exc_info()[1])
                    return False 
Example 41
Project: aws-auto-remediate   Author: servian   File: config_rules.py    License: GNU General Public License v3.0 5 votes vote down vote up
def s3_bucket_server_side_encryption_enabled(self, resource_id):
        """Enables Server-side Encryption for an S3 Bucket
        
        Arguments:
            resource_id {string} -- S3 Bucket name
        
        Returns:
            boolean -- True if remediation is successful
        """
        try:
            self.client_s3.put_bucket_encryption(
                Bucket=resource_id,
                ServerSideEncryptionConfiguration={
                    "Rules": [
                        {
                            "ApplyServerSideEncryptionByDefault": {
                                "SSEAlgorithm": "AES256"
                            }
                        }
                    ]
                },
            )
            self.logging.info(
                f"Enabled Server-side Encryption for S3 Bucket '{resource_id}'."
            )
            return True
        except:
            self.logging.info(
                f"Could not enable Server-side Encryption for S3 Bucket '{resource_id}'."
            )
            self.logging.error(sys.exc_info()[1])
            return False 
Example 42
Project: aws-auto-remediate   Author: servian   File: config_rules.py    License: GNU General Public License v3.0 5 votes vote down vote up
def s3_bucket_ssl_requests_only(self, resource_id):
        """Adds Bucket Policy to force SSL only connections
        
        Arguments:
            resource_id {string} -- S3 Bucket name
        
        Returns:
            boolean -- True if remediation was successful
        """

        # get SSL policy
        policy_file = "auto_remediate/data/s3_bucket_ssl_requests_only_policy.json"
        with open(policy_file, "r") as file:
            policy = file.read()

        policy = json.loads(policy.replace("_BUCKET_", resource_id))

        try:
            response = self.client_s3.get_bucket_policy(Bucket=resource_id)
        except ClientError as error:
            if error.response["Error"]["Code"] == "NoSuchBucketPolicy":
                return self.set_bucket_policy(resource_id, json.dumps(policy))
            else:
                self.logging.error(
                    f"Could not set SSL requests only policy to S3 Bucket '{resource_id}'."
                )
                self.logging.error(sys.exc_info()[1])
                return False
        except:
            self.logging.error(
                f"Could not retrieve existing policy to S3 Bucket '{resource_id}'."
            )
        else:
            existing_policy = json.loads(response["Policy"])
            existing_policy["Statement"].append(policy["Statement"][0])

            return self.set_bucket_policy(resource_id, json.dumps(existing_policy)) 
Example 43
Project: aws-auto-remediate   Author: servian   File: security_hub_rules.py    License: GNU General Public License v3.0 5 votes vote down vote up
def access_keys_rotated(self, resource_id):
        """Deletes IAM User's Access Keys over 90 days old.
        
        Arguments:
            resource_id {string} -- IAM Access Key ID
        
        Returns:
            boolean -- True if remediation is successful
        """
        try:
            response = self.client_iam.get_access_key_last_used(AccessKeyId=resource_id)
        except:
            self.logging.error(
                f"Could not retrieve IAM User Name for IAM Access Key '{resource_id}'."
            )
            self.logging.error(sys.exc_info()[1])
            return False
        else:
            user_name = response["UserName"]
            self.logging.info(
                f"Retrieved IAM User Name '{user_name}' for IAM Access Key '{resource_id}'."
            )

        try:
            self.client_iam.delete_access_key(
                UserName=user_name, AccessKeyId=resource_id
            )
            self.logging.info(
                f"Deleted unrotated IAM Access Key '{resource_id}' for IAM User Name '{user_name}'."
            )
            return True
        except:
            self.logging.error(
                f"Could not delete unrotated IAM Access Key '{resource_id}' for IAM User Name '{user_name}'."
            )
            self.logging.error(sys.exc_info()[1])
            return False 
Example 44
Project: aws-auto-remediate   Author: servian   File: security_hub_rules.py    License: GNU General Public License v3.0 5 votes vote down vote up
def cmk_backing_key_rotation_enabled(self, resource_id):
        """Enables key rotation for KMS Customer Managed Keys.
        
        Arguments:
            resource_id {string} -- KMS Key ID
        
        Returns:
            boolean -- True if remediation was successful
        """
        try:
            self.client_kms.enable_key_rotation(KeyId=resource_id)
            self.logging.info(
                f"Enabled key rotation for KMS Customer Managed Key '{resource_id}'."
            )
            return True
        except self.client_kms.exceptions.KMSInvalidStateException:
            self.logging.warning(
                f"Could not enable key rotation for KMS Customer Managed Key '{resource_id}' due to invalid state."
            )
            self.logging.warning(sys.exc_info()[1])
            return False
        except:
            self.logging.error(
                f"Could not enable key rotation for KMS Customer Managed Key '{resource_id}'."
            )
            self.logging.error(sys.exc_info()[1])
            return False 
Example 45
Project: aws-auto-remediate   Author: servian   File: security_hub_rules.py    License: GNU General Public License v3.0 5 votes vote down vote up
def iam_password_policy(self, resource_id):
        """Applies a sensible IAM password policy, as per CIS AWS Foundations Standard Checks Supported in Security Hub
        1.5 - Ensure IAM password policy requires at least one uppercase letter
        1.6 - Ensure IAM password policy requires at least one lowercase letter
        1.7 - Ensure IAM password policy requires at least one symbol
        1.8 - Ensure IAM password policy requires at least one number
        1.9 - Ensure IAM password policy requires a minimum length of 14 or greater
        1.10 - Ensure IAM password policy prevents password reuse
        1.11 - Ensure IAM password policy expires passwords within 90 days or less
        
        Arguments:
            resource_id {string} -- AWS Account ID
        
        Returns:
            boolean -- True if remediation was succesfull
        """
        try:
            self.client_iam.update_account_password_policy(
                MinimumPasswordLength=14,  # 14 characters
                RequireSymbols=True,
                RequireNumbers=True,
                RequireUppercaseCharacters=True,
                RequireLowercaseCharacters=True,
                AllowUsersToChangePassword=True,
                MaxPasswordAge=90,  # days
                PasswordReusePrevention=24,  # last 24 passwords
                HardExpiry=False,
            )
            self.logging.info(
                f"Updated IAM password policy with CIS AWS Foundations "
                f"requirements for Account '{resource_id}'."
            )
            return True
        except:
            self.logging.error(
                f"Could not update IAM password policy for Account '{resource_id}'."
            )
            self.logging.error(sys.exc_info()[1])
            return False 
Example 46
Project: aws-auto-remediate   Author: servian   File: security_hub_rules.py    License: GNU General Public License v3.0 5 votes vote down vote up
def iam_user_no_policies_check(self, resource_id):
        """ Detaches user policies from IAM user

        Arguments:
            resource_id {string} -- IAM User ID

        Returns:
            boolean -- True if remediation was successful
        """
        try:
            page_user = self.client_iam.get_paginator("list_users").paginate()
            for username in page_user.search(
                f"Users[?UserId == '{resource_id}'].UserName"
            ):
                page_policy = self.client_iam.get_paginator(
                    "list_attached_user_policies"
                ).paginate(UserName=username)
                for policy_arn in page_policy.search(f"AttachedPolicies[].PolicyArn"):
                    self.client_iam.detach_user_policy(
                        UserName=username, PolicyArn=policy_arn
                    )
                    self.logging.info(
                        f"Detached IAM Policy '{policy_arn}' from IAM User '{username}'."
                    )
                    return True
        except:
            self.logging.error(
                f"Could not detach IAM Policy '{policy_arn}' from IAM User '{username}'."
            )
            self.logging.error(sys.exc_info()[1])
            return False 
Example 47
Project: aws-auto-remediate   Author: servian   File: security_hub_rules.py    License: GNU General Public License v3.0 5 votes vote down vote up
def restricted_ssh(self, resource_id):
        """Deletes inbound rules within Security Groups that match:
            Protocol: TCP
            Port: 22
            Source: 0.0.0.0/0 or ::/0
        
        Arguments:
            resource_id {string} -- EC2 Security Group ID
        
        Returns:
            boolean -- True if remediation was successful
        """
        try:
            self.client_ec2.revoke_security_group_ingress(
                GroupId=resource_id,
                IpPermissions=[
                    {
                        "FromPort": 22,
                        "ToPort": 22,
                        "IpProtocol": "tcp",
                        "IpRanges": [{"CidrIp": "0.0.0.0/0"}],
                    },
                    {
                        "FromPort": 22,
                        "ToPort": 22,
                        "IpProtocol": "tcp",
                        "Ipv6Ranges": [{"CidrIpv6": "::/0"}],
                    },
                ],
            )

            self.logging.info(
                f"Revoked public port 22 ingress rule for Security Group '{resource_id}'."
            )
            return True
        except:
            self.logging.error(
                f"Could not revoke public port 22 ingress rule for Security Group '{resource_id}'."
            )
            self.logging.error(sys.exc_info()[1])
            return False 
Example 48
Project: aws-auto-remediate   Author: servian   File: security_hub_rules.py    License: GNU General Public License v3.0 5 votes vote down vote up
def delete_log_group(self, log_group_name):
        try:
            self.client_logs.delete_log_group(logGroupName=log_group_name)
            self.logging.info(f"Deleted CloudWatch Log Group '{log_group_name}'.")
        except:
            self.logging.error(
                f"Could not delete CloudWatch Log Group '{log_group_name}'."
            )
            self.logging.error(sys.exc_info()[1]) 
Example 49
Project: aws-auto-remediate   Author: servian   File: security_hub_rules.py    License: GNU General Public License v3.0 5 votes vote down vote up
def delete_role(self, role_name):
        try:
            self.client_iam.delete_role(RoleName=role_name)
            self.logging.info(f"Deleted IAM Role '{role_name}'.")
        except:
            self.logging.error(f"Could not delete IAM Role '{role_name}'.")
            self.logging.error(sys.exc_info()[1]) 
Example 50
Project: aws-auto-remediate   Author: servian   File: security_hub_rules.py    License: GNU General Public License v3.0 5 votes vote down vote up
def delete_role_policy(self, role_name, iam_policy_name):
        try:
            self.client_iam.delete_role_policy(
                RoleName=role_name, PolicyName=iam_policy_name
            )
            self.logging.info(
                f"Deleted IAM Policy '{iam_policy_name}' from IAM Role '{role_name}'."
            )
        except:
            self.logging.error(
                f"Could not delete IAM Policy '{iam_policy_name}' from IAM Role '{role_name}'."
            )
            self.logging.error(sys.exc_info()[1])

    # KMS 
Example 51
Project: aws-auto-remediate   Author: servian   File: lambda_handler.py    License: GNU General Public License v3.0 5 votes vote down vote up
def send_to_dead_letter_queue(self, config_payload, try_count):
        """Sends the AWS Config payload to an SQS Queue (DLQ) if after incrementing 
        the "try_count" variable it is below the user defined "RETRYCOUNT" setting.
        
        Arguments:
            config_payload {dictionary} -- AWS Config payload
            try_count {string} -- Number of previos remediation attemps for this AWS Config payload
        """
        client = boto3.client("sqs")

        try_count = int(try_count) + 1
        if try_count < int(os.environ.get("RETRYCOUNT", 3)):
            try:
                client.send_message(
                    QueueUrl=os.environ["DEADLETTERQUEUE"],
                    MessageBody=json.dumps(config_payload),
                    MessageAttributes={
                        "try_count": {
                            "StringValue": str(try_count),
                            "DataType": "Number",
                        }
                    },
                )

                self.logging.debug(
                    f"Remediation failed. Payload has been sent to SQS DLQ '{os.environ['DEADLETTERQUEUE']}'."
                )
            except:
                self.logging.error(
                    f"Could not send payload to SQS DLQ '{os.environ['DEADLETTERQUEUE']}'."
                )
                self.logging.error(sys.exc_info()[1])
        else:
            self.logging.warning(
                f"Could not remediate Config change within an "
                f"acceptable number of retries for payload '{config_payload}'."
            ) 
Example 52
Project: aws-auto-remediate   Author: servian   File: lambda_handler.py    License: GNU General Public License v3.0 5 votes vote down vote up
def send_to_compliance_queue(self, config_payload, try_count):
        """Sends a message to the Config Compliance SQS Queue.
        
        Arguments:
            config_payload {string} -- AWS Config payload
            try_count {string} -- Number of attempted remediations for a given AWS Config Rule
        
        Returns:
            boolean -- True if sending message to SQS was successful
        """
        queue_url = os.environ.get("COMPLIANCEQUEUE")

        try:
            self.client_sqs.send_message(
                QueueUrl=queue_url,
                MessageBody=config_payload,
                MessageAttributes={
                    "try_count": {"StringValue": try_count, "DataType": "Number"}
                },
            )

            self.logging.debug(f"Message payload sent to SQS Queue '{queue_url}'.")
            return True
        except:
            self.logging.error(f"Could not send payload to SQS Queue '{queue_url}'.")
            self.logging.error(sys.exc_info()[1])
            return False 
Example 53
Project: CAMISIM   Author: CAMI-challenge   File: anim.py    License: Apache License 2.0 5 votes vote down vote up
def last_exception():
		"""
		Returns last exception as a string, or use in logging.

		@rtype: str|unicode
		"""
		exc_type, exc_value, exc_traceback = sys.exc_info()
		return ''.join(traceback.format_exception(exc_type, exc_value, exc_traceback))

	# Parse NUCmer delta output to store alignment total length, sim_error,
	# and percentage identity, for each pairwise comparison 
Example 54
Project: friendly-telegram   Author: friendly-telegram   File: python.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def evalcmd(self, message):
        """.eval <expression>
           Evaluates python code"""
        ret = self.strings["evaluated"]
        try:
            it = await meval(utils.get_args_raw(message), globals(), **await self.getattrs(message))
        except Exception:
            exc = sys.exc_info()
            exc = "".join(traceback.format_exception(exc[0], exc[1], exc[2].tb_next.tb_next.tb_next))
            await utils.answer(message, self.strings["evaluate_fail"]
                               .format(utils.escape_html(utils.get_args_raw(message)), utils.escape_html(exc)))
            return
        ret = ret.format(utils.escape_html(utils.get_args_raw(message)), utils.escape_html(it))
        await utils.answer(message, ret) 
Example 55
Project: friendly-telegram   Author: friendly-telegram   File: python.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def execcmd(self, message):
        """.exec <expression>
           Executes python code"""
        try:
            await meval(utils.get_args_raw(message), globals(), **await self.getattrs(message))
        except Exception:
            exc = sys.exc_info()
            exc = "".join(traceback.format_exception(exc[0], exc[1], exc[2].tb_next.tb_next.tb_next))
            await utils.answer(message, self.strings["execute_fail"]
                               .format(utils.escape_html(utils.get_args_raw(message)), utils.escape_html(exc)))
            return 
Example 56
Project: NiBetaSeries   Author: HBClab   File: versioneer.py    License: 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 57
Project: NiBetaSeries   Author: HBClab   File: _version.py    License: 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 58
Project: SecPi   Author: SecPi   File: main.py    License: GNU General Public License v3.0 5 votes vote down vote up
def handle_error(self):
		if('Content-Type' in cherrypy.request.headers and 'application/json' in cherrypy.request.headers['Content-Type'].lower()):
			exc_type, exc_value, exc_traceback = sys.exc_info()
			cherrypy.response.status = 200
			cherrypy.response.body = json.dumps({'status':'error', 'message': "An exception occured during processing! %s"%exc_value, 'traceback':traceback.format_exc() })
		else:
			tmpl = self.lookup.get_template("500.mako")
			cherrypy.response.status = 500
			cherrypy.response.body = tmpl.render(page_title="Error!", traceback=traceback.format_exc()) 
Example 59
Project: soccer-matlab   Author: utra-robosoccer   File: wrappers.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _worker(self, constructor, conn):
    """The process waits for actions and sends back environment results.

    Args:
      constructor: Constructor for the OpenAI Gym environment.
      conn: Connection for communication to the main process.
    """
    try:
      env = constructor()
      while True:
        try:
          # Only block for short times to have keyboard exceptions be raised.
          if not conn.poll(0.1):
            continue
          message, payload = conn.recv()
        except (EOFError, KeyboardInterrupt):
          break
        if message == self._ACTION:
          action = payload
          conn.send((self._TRANSITION, env.step(action)))
          continue
        if message == self._RESET:
          assert payload is None
          conn.send((self._OBSERV, env.reset()))
          continue
        if message == self._ATTRIBUTE:
          name = payload
          conn.send((self._VALUE, getattr(env, name)))
          continue
        if message == self._CLOSE:
          assert payload is None
          break
        raise KeyError('Received message of unknown type {}'.format(message))
    except Exception:  # pylint: disable=broad-except
      stacktrace = ''.join(traceback.format_exception(*sys.exc_info()))
      conn.send((self._EXCEPTION, stacktrace))
      tf.logging.error('Error in environment process: {}'.format(stacktrace))
    conn.close() 
Example 60
Project: soccer-matlab   Author: utra-robosoccer   File: wrappers.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _worker(self, constructor, conn):
    """The process waits for actions and sends back environment results.

    Args:
      constructor: Constructor for the OpenAI Gym environment.
      conn: Connection for communication to the main process.
    """
    try:
      env = constructor()
      while True:
        try:
          # Only block for short times to have keyboard exceptions be raised.
          if not conn.poll(0.1):
            continue
          message, payload = conn.recv()
        except (EOFError, KeyboardInterrupt):
          break
        if message == self._ACCESS:
          name = payload
          result = getattr(env, name)
          conn.send((self._RESULT, result))
          continue
        if message == self._CALL:
          name, args, kwargs = payload
          result = getattr(env, name)(*args, **kwargs)
          conn.send((self._RESULT, result))
          continue
        if message == self._CLOSE:
          assert payload is None
          break
        raise KeyError('Received message of unknown type {}'.format(message))
    except Exception:  # pylint: disable=broad-except
      stacktrace = ''.join(traceback.format_exception(*sys.exc_info()))
      tf.logging.error('Error in environment process: {}'.format(stacktrace))
      conn.send((self._EXCEPTION, stacktrace))
    conn.close()