Python sys.html() Examples

The following are 30 code examples of sys.html(). 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: pySmartDL.py    From pySmartDL with The Unlicense 6 votes vote down vote up
def add_hash_verification(self, algorithm, hash):
        '''
        Adds hash verification to the download.
        
        If hash is not correct, will try different mirrors. If all mirrors aren't
        passing hash verification, `HashFailedException` Exception will be raised.
        
        .. NOTE::
            If downloaded file already exist on the destination, and hash matches, pySmartDL will not download it again.
            
        .. WARNING::
            The hashing algorithm must be supported on your system, as documented at `hashlib documentation page <http://docs.python.org/3/library/hashlib.html>`_.
        
        :param algorithm: Hashing algorithm.
        :type algorithm: string
        :param hash: Hash code.
        :type hash: string
        '''
        
        self.verify_hash = True
        self.hash_algorithm = algorithm
        self.hash_code = hash 
Example #2
Source File: logbook.py    From apm-agent-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _emit(self, record):
        # If there's no exception being processed,
        # exc_info may be a 3-tuple of None
        # http://docs.python.org/library/sys.html#sys.exc_info
        if record.exc_info is True or (record.exc_info and all(record.exc_info)):
            handler = self.client.get_handler("elasticapm.events.Exception")
            exception = handler.capture(self.client, exc_info=record.exc_info)
        else:
            exception = None

        return self.client.capture_message(
            param_message={"message": compat.text_type(record.msg), "params": record.args},
            exception=exception,
            level=LOOKBOOK_LEVELS[record.level],
            logger_name=record.channel,
            custom=record.extra,
            stack=record.kwargs.get("stack"),
        ) 
Example #3
Source File: cli.py    From cookiecutter-conda-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def cli(args=None):
    p = ArgumentParser(
        description="{{ cookiecutter['project_short_description']}}",
        conflict_handler='resolve'
    )
    p.add_argument(
        '-V', '--version',
        action='version',
        help='Show the conda-prefix-replacement version number and exit.',
        version="{{ cookiecutter['package_name']}} %s" % __version__,
    )

    args = p.parse_args(args)

    # do something with the args
    print("CLI template - fix me up!")

    # No return value means no error.
    # Return a value of 1 or higher to signify an error.
    # See https://docs.python.org/3/library/sys.html#sys.exit 
Example #4
Source File: base.py    From jbox with MIT License 6 votes vote down vote up
def load_wsgi(self):
        try:
            self.wsgi = self.app.wsgi()
        except SyntaxError as e:
            if not self.cfg.reload:
                raise

            self.log.exception(e)

            # fix from PR #1228
            # storing the traceback into exc_tb will create a circular reference.
            # per https://docs.python.org/2/library/sys.html#sys.exc_info warning,
            # delete the traceback after use.
            try:
                exc_type, exc_val, exc_tb = sys.exc_info()
                self.reloader.add_extra_file(exc_val.filename)

                tb_string = traceback.format_tb(exc_tb)
                self.wsgi = util.make_fail_app(tb_string)
            finally:
                del exc_tb 
Example #5
Source File: controllers.py    From BlackSheep with MIT License 6 votes vote down vote up
def view(self,
             name: Optional[str] = None,
             model: Optional[Any] = None) -> Response:
        """
        Returns a view rendered synchronously.

        :param name: name of the template (path to the template file, optionally without '.html' extension
        :param model: optional model, required to render the template.
        :return: a Response object
        """
        if not name:
            name = self.get_default_view_name()

        if model:
            return view(self.templates, self.full_view_name(name), **model)
        return view(self.templates, self.full_view_name(name)) 
Example #6
Source File: container.py    From benchexec with Apache License 2.0 6 votes vote down vote up
def chroot(target):
    """
    Chroot into a target directory. This also affects the working directory, make sure
    to call os.chdir() afterwards.
    """
    # We need to use pivot_root and not only chroot
    # (cf. https://unix.stackexchange.com/a/456777/15398).
    # These three steps together are the easiest way for calling pivot_root as chroot
    # replacement (cf. the 'pivot_root(".", ".")' section of
    # http://man7.org/linux/man-pages/man2/pivot_root.2.html).
    os.chdir(target)
    # Make "." (the target) our new root and put the old root at ".":
    libc.pivot_root(b".", b".")
    # Now both the host file system (old root) and the target are at "/" (stacked).
    # We umount one of them, which will be the host file system, making it inaccessible:
    libc.umount2(b"/", libc.MNT_DETACH) 
Example #7
Source File: didyoumean_internal.py    From DidYouMean-Python with MIT License 6 votes vote down vote up
def get_types_for_str(tp_name, frame):
    """Get a list of candidate types from a string.

    String corresponds to the tp_name as described in :
    https://docs.python.org/2/c-api/typeobj.html#c.PyTypeObject.tp_name
    as it is the name used in exception messages. It may include full path
    with module, subpackage, package but this is just removed in current
    implementation to search only based on the type name.

    Lookup uses both class hierarchy and name lookup as the first may miss
    old style classes on Python 2 and second does find them.
    Just like get_types_for_str_using_inheritance, this needs to be called
    as late as possible but because it requires a frame, there is not much
    choice anyway.
    """
    name = tp_name.split('.')[-1]
    res = set.union(
        get_types_for_str_using_inheritance(name),
        get_types_for_str_using_names(name, frame))
    assert all(inspect.isclass(t) and t.__name__ == name for t in res)
    return res 
Example #8
Source File: utils.py    From contrail-api-cli with MIT License 6 votes vote down vote up
def printo(msg, encoding=None, errors='replace', std_type='stdout'):
    """Write msg on stdout. If no encoding is specified
    the detected encoding of stdout is used. If the encoding
    can't encode some chars they are replaced by '?'

    :param msg: message
    :type msg: unicode on python2 | str on python3
    """
    std = getattr(sys, std_type, sys.stdout)
    if encoding is None:
        try:
            encoding = std.encoding
        except AttributeError:
            encoding = None
    # Fallback to ascii if no encoding is found
    if encoding is None:
        encoding = 'ascii'
    # https://docs.python.org/3/library/sys.html#sys.stdout
    # write in the binary buffer directly in python3
    if hasattr(std, 'buffer'):
        std = std.buffer
    std.write(msg.encode(encoding, errors=errors))
    std.write(b'\n')
    std.flush() 
Example #9
Source File: controllers.py    From BlackSheep with MIT License 6 votes vote down vote up
def view_async(self,
                         name: Optional[str] = None,
                         model: Optional[Any] = None) -> Response:
        """
        Returns a view rendered asynchronously.

        :param name: name of the template (path to the template file, optionally without '.html' extension
        :param model: optional model, required to render the template.
        :return: a Response object
        """
        if not name:
            name = self.get_default_view_name()

        if model:
            return await view_async(self.templates, self.full_view_name(name), **model)
        return await view_async(self.templates, self.full_view_name(name)) 
Example #10
Source File: monitoring.py    From satori with Apache License 2.0 6 votes vote down vote up
def _handle_exception():
    """Print exceptions raised by subscribers to stderr."""
    # Heavily influenced by logging.Handler.handleError.

    # See note here:
    # https://docs.python.org/3.4/library/sys.html#sys.__stderr__
    if sys.stderr:
        einfo = sys.exc_info()
        try:
            traceback.print_exception(einfo[0], einfo[1], einfo[2],
                                      None, sys.stderr)
        except IOError:
            pass
        finally:
            del einfo

# Note - to avoid bugs from forgetting which if these is all lowercase and
# which are camelCase, and at the same time avoid having to add a test for
# every command, use all lowercase here and test against command_name.lower(). 
Example #11
Source File: pySmartDL.py    From kano-burners with GNU General Public License v2.0 6 votes vote down vote up
def add_hash_verification(self, algorithm, hash):
        '''
        Adds hash verification to the download.

        If hash is not correct, will try different mirrors. If all mirrors aren't
        passing hash verification, `HashFailedException` Exception will be raised.

        .. NOTE::
            If downloaded file already exist on the destination, and hash matches, pySmartDL will not download it again.

        .. WARNING::
            The hashing algorithm must be supported on your system, as documented at `hashlib documentation page <http://docs.python.org/2/library/hashlib.html>`_.

        :param algorithm: Hashing algorithm.
        :type algorithm: string
        :param hash: Hash code.
        :type hash: string
        '''

        self.verify_hash = True
        self.hash_algorithm = algorithm
        self.hash_code = hash 
Example #12
Source File: failure.py    From taskflow with Apache License 2.0 5 votes vote down vote up
def exc_info(self):
        """Exception info tuple or none.

        See: https://docs.python.org/2/library/sys.html#sys.exc_info for what
             the contents of this tuple are (if none, then no contents can
             be examined).
        """
        return self._exc_info 
Example #13
Source File: controllers.py    From BlackSheep with MIT License 5 votes vote down vote up
def _get_route_handler_name(self):
        """Returns the name of the closest route handler in the call stack.

        Note: this function is designed to improve user's experience when using the framework.
        It removes the need to explicit the name of the template when using the `view()` function.

        It uses sys._getframe, which is a CPython implementation detail and is not guaranteed to be
        to exist in all implementations of Python.
        https://docs.python.org/3/library/sys.html
        """
        i = 2  # Note: no need to get the frame for this function and the direct caller;
        while True:
            i += 1
            try:
                fn_meta = sys._getframe(i).f_code
            except AttributeError:
                # NB: if sys._getframe raises attribute error, it means is not supported
                # by the used Python runtime; return None; which in turn will cause an exception.
                return None
            except ValueError:
                break
            fn = getattr(self, fn_meta.co_name, None)

            if not fn:
                continue

            try:
                if fn.route_handler:
                    return fn_meta.co_name
            except AttributeError:
                pass
        return None 
Example #14
Source File: cache.py    From python-tools with MIT License 5 votes vote down vote up
def __init__(self):
        self.__index = None
        self.py_tag = 'cpython-%s%s' % sys.version_info[:2]
        """
        Short name for distinguish Python implementations and versions.

        It's like `sys.implementation.cache_tag` but for Python < 3.3
        we generate something similar.  See:
        http://docs.python.org/3/library/sys.html#sys.implementation

        .. todo:: Detect interpreter (e.g., PyPy).
        """ 
Example #15
Source File: sandbox.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def _install_import_hooks(config, path_override_hook):
  """Install runtime's import hooks.

  These hooks customize the import process as per
  https://docs.python.org/2/library/sys.html#sys.meta_path .

  Args:
    config: An apphosting/tools/devappserver2/runtime_config.proto
        for this instance.
    path_override_hook: A hook for importing special appengine
        versions of select libraries from the libraries
        section of the current module's app.yaml file.
  """
  if not config.vm:
    enabled_regexes = THIRD_PARTY_C_MODULES.get_enabled_regexes(config)
    sys.meta_path = [
        StubModuleImportHook(),
        ModuleOverrideImportHook(_MODULE_OVERRIDE_POLICIES),
        CModuleImportHook(enabled_regexes),
        path_override_hook,
        PyCryptoRandomImportHook,
        PathRestrictingImportHook(enabled_regexes)]
  else:
    sys.meta_path = [
        # Picks up custom versions of certain libraries in the libraries section
        #     of app.yaml
        path_override_hook,
        # Picks up a custom version of Crypto.Random.OSRNG.posix.
        # TODO: Investigate removing this as it may not be needed
        #     for vms since they are able to read /dev/urandom, I left it for
        #     consistency.
        PyCryptoRandomImportHook] 
Example #16
Source File: failure.py    From taskflow with Apache License 2.0 5 votes vote down vote up
def __ne__(self, other):
        return not (self == other)

    # NOTE(imelnikov): obj.__hash__() should return same values for equal
    # objects, so we should redefine __hash__. Failure equality semantics
    # is a bit complicated, so for now we just mark Failure objects as
    # unhashable. See python docs on object.__hash__  for more info:
    # http://docs.python.org/2/reference/datamodel.html#object.__hash__ 
Example #17
Source File: runLog.py    From armi with Apache License 2.0 5 votes vote down vote up
def __init__(self, verbosity=50):  # pylint: disable=unused-argument
        """
        Build a log object

        Parameters
        ----------
        verbosity : int
            if a msg verbosity is > this, it will be  emitted.
            The default of 50 means only error messages will be emitted.
            This usually gets adjusted by user settings quickly after instantiation.

        """
        self._verbosity = verbosity
        self._singleMessageCounts = collections.defaultdict(lambda: 0)
        self._singleWarningMessageCounts = collections.defaultdict(lambda: 0)
        self._outputStream = None
        self._errStream = None
        # https://docs.python.org/2/library/sys.html says
        # to explicitly save these instead of relying upon __stdout__, etc.
        if context.MPI_RANK == 0:
            self.initialOut = sys.stdout
            self.initialErr = sys.stderr
        else:
            # Attach output streams to a null device until we open log files. We don't know what to
            # call them until we have processed some of the settings, and any errors encountered in
            # that should be encountered on the master process anyway.
            self.initialOut = open(os.devnull, "w")
            self.initialErr = open(os.devnull, "w")
        self.setStreams(self.initialOut, self.initialErr)
        self.name = "log" 
Example #18
Source File: cache.py    From CNCGToolKit with MIT License 5 votes vote down vote up
def __init__(self):
        self.__index = None
        self.py_tag = 'cpython-%s%s' % sys.version_info[:2]
        """
        Short name for distinguish Python implementations and versions.

        It's like `sys.implementation.cache_tag` but for Python < 3.3
        we generate something similar.  See:
        http://docs.python.org/3/library/sys.html#sys.implementation

        .. todo:: Detect interpreter (e.g., PyPy).
        """ 
Example #19
Source File: utils.py    From autocomplete-python with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self):
        self.__index = None
        self.py_tag = 'cpython-%s%s' % sys.version_info[:2]
        """
        Short name for distinguish Python implementations and versions.

        It's like `sys.implementation.cache_tag` but for Python < 3.3
        we generate something similar.  See:
        http://docs.python.org/3/library/sys.html#sys.implementation

        .. todo:: Detect interpreter (e.g., PyPy).
        """ 
Example #20
Source File: bootstrap.py    From knative-lambda-runtime with Apache License 2.0 5 votes vote down vote up
def set_default_sys_path():
    if not is_pythonpath_set():
        sys.path.insert(0, get_opt_python_directory())
        sys.path.insert(0, get_opt_site_packages_directory())
    # '/var/task' is function author's working directory
    # we add it first in order to mimic the default behavior of populating sys.path and make modules under '/var/task'
    # discoverable - https://docs.python.org/3/library/sys.html#sys.path
    sys.path.insert(0, os.environ['LAMBDA_TASK_ROOT']) 
Example #21
Source File: bootstrap.py    From knative-lambda-runtime with Apache License 2.0 5 votes vote down vote up
def set_default_sys_path():
    if not is_pythonpath_set():
        sys.path.insert(0, get_opt_python_directory())
        sys.path.insert(0, get_opt_site_packages_directory())
    # '/var/task' is function author's working directory
    # we add it first in order to mimic the default behavior of populating sys.path and make modules under '/var/task'
    # discoverable - https://docs.python.org/3/library/sys.html#sys.path
    sys.path.insert(0, os.environ['LAMBDA_TASK_ROOT']) 
Example #22
Source File: misc.py    From workload-automation with Apache License 2.0 5 votes vote down vote up
def get_traceback(exc=None):
    """
    Returns the string with the traceback for the specifiec exc
    object, or for the current exception exc is not specified.

    """
    if exc is None:
        exc = sys.exc_info()
    if not exc:
        return None
    tb = exc[2]
    sio = StringIO()
    traceback.print_tb(tb, file=sio)
    del tb  # needs to be done explicitly see: http://docs.python.org/2/library/sys.html#sys.exc_info
    return sio.getvalue() 
Example #23
Source File: helpers.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _handle_exception():
    """Print exceptions raised by subscribers to stderr."""
    # Heavily influenced by logging.Handler.handleError.

    # See note here:
    # https://docs.python.org/3.4/library/sys.html#sys.__stderr__
    if sys.stderr:
        einfo = sys.exc_info()
        try:
            traceback.print_exception(einfo[0], einfo[1], einfo[2],
                                      None, sys.stderr)
        except IOError:
            pass
        finally:
            del einfo 
Example #24
Source File: helpers.py    From opsbro with MIT License 5 votes vote down vote up
def _handle_exception():
    """Print exceptions raised by subscribers to stderr."""
    # Heavily influenced by logging.Handler.handleError.

    # See note here:
    # https://docs.python.org/3.4/library/sys.html#sys.__stderr__
    if sys.stderr:
        einfo = sys.exc_info()
        try:
            traceback.print_exception(einfo[0], einfo[1], einfo[2],
                                      None, sys.stderr)
        except IOError:
            pass
        finally:
            del einfo 
Example #25
Source File: helpers.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def _handle_exception():
    """Print exceptions raised by subscribers to stderr."""
    # Heavily influenced by logging.Handler.handleError.

    # See note here:
    # https://docs.python.org/3.4/library/sys.html#sys.__stderr__
    if sys.stderr:
        einfo = sys.exc_info()
        try:
            traceback.print_exception(einfo[0], einfo[1], einfo[2],
                                      None, sys.stderr)
        except IOError:
            pass
        finally:
            del einfo 
Example #26
Source File: setup.py    From LLDBagility with Apache License 2.0 5 votes vote down vote up
def build_libraries(self, libraries):
        # enough for LLDBagility; follow the installation instructions at FDPutils/README.md
        return
        # platform description refers at https://docs.python.org/2/library/sys.html#sys.platform
        if not sys.platform == "win32":
            raise ValueError("Can not build on a platform that is not native Windows")
        

        assert self.vs in VS_VERSIONS, 'Unrecognized visual studio compiler version. Supported versions : %s ' % ",".join(VS_VERSIONS)
        log.info("building FPD library with visual studio %s " % self.vs)

        _cwd = os.getcwd()
        os.chdir(ROOT_DIRECTORY)

        # Cleanup old build folders
        shutil.rmtree(os.path.join(ROOT_DIRECTORY, "out_x64"), ignore_errors=True)
        shutil.rmtree(os.path.join(ROOT_DIRECTORY, "out_x86"), ignore_errors=True)

        # Windows build: this process requires few things:
        #    - CMake + MSVC installed
        #    - Run this command in an environment setup for MSVC
        os.system(FDP_BUILD_SCRIPT(self.vs))
        if not os.path.exists(PATH_LIB64):
            raise FileNotFoundError("Could not find %s : compilation step went wrong", PATH_LIB64)
        if not os.path.exists(PATH_LIB32):
            raise FileNotFoundError("Could not find %s : compilation step went wrong", PATH_LIB32)

        # copy compiled dll files into source dir
        shutil.copy(PATH_LIB32, os.path.join(BINDING_DIRECTORY, "PyFDP", "FDP_x86.dll"))
        shutil.copy(PATH_LIB64, os.path.join(BINDING_DIRECTORY, "PyFDP", "FDP_x64.dll"))

        os.chdir(_cwd) 
Example #27
Source File: cache.py    From NukeToolSet with MIT License 5 votes vote down vote up
def __init__(self):
        self.__index = None
        self.py_tag = 'cpython-%s%s' % sys.version_info[:2]
        """
        Short name for distinguish Python implementations and versions.

        It's like `sys.implementation.cache_tag` but for Python < 3.3
        we generate something similar.  See:
        http://docs.python.org/3/library/sys.html#sys.implementation

        .. todo:: Detect interpreter (e.g., PyPy).
        """ 
Example #28
Source File: pySmartDL.py    From kano-burners with GNU General Public License v2.0 5 votes vote down vote up
def download(url, dest, startByte=0, endByte=None, headers=None, timeout=4, shared_var=None, thread_shared_cmds=None, logger=None, retries=1):
    "The basic download function that runs at each thread."
    logger = logger or utils.DummyLogger()
    if not headers:
        headers = {}
    if endByte:
        headers['Range'] = 'bytes=%d-%d' % (startByte, endByte)

    logger.debug("Downloading '%s' to '%s'..." % (url, dest))
    req = urllib2.Request(url, headers=headers)
    try:
        urlObj = urllib2.urlopen(req, timeout=timeout)
    except urllib2.HTTPError, e:
        if e.code == 416:
            '''
            HTTP 416 Error: Requested Range Not Satisfiable. Happens when we ask
            for a range that is not available on the server. It will happen when
            the server will try to send us a .html page that means something like
            "you opened too many connections to our server". If this happens, we
            will wait for the other threads to finish their connections and try again.
            '''

            if retries > 0:
                logger.warning("Thread didn't got the file it was expecting. Retrying (%d times left)..." % (retries-1))
                time.sleep(5)
                return download(url, dest, startByte, endByte, headers, timeout, shared_var, thread_shared_cmds, logger, retries-1)
            else:
                raise
        else:
            raise 
Example #29
Source File: pySmartDL.py    From kano-burners with GNU General Public License v2.0 5 votes vote down vote up
def get_data_hash(self, algorithm):
        '''
        Returns the downloaded data's hash. Will raise `RuntimeError` if it's
        called when the download task is not finished yet.

        :param algorithm: Hashing algorithm.
        :type algorithm: bool
        :rtype: string

        .. WARNING::
            The hashing algorithm must be supported on your system, as documented at `hashlib documentation page <http://docs.python.org/2/library/hashlib.html>`_.
        '''
        return hashlib.new(algorithm, self.get_data(binary=True)).hexdigest() 
Example #30
Source File: cache.py    From Computable with MIT License 5 votes vote down vote up
def __init__(self):
        self.__index = None
        self.py_tag = 'cpython-%s%s' % sys.version_info[:2]
        """
        Short name for distinguish Python implementations and versions.

        It's like `sys.implementation.cache_tag` but for Python < 3.3
        we generate something similar.  See:
        http://docs.python.org/3/library/sys.html#sys.implementation

        .. todo:: Detect interpreter (e.g., PyPy).
        """