How to use the trio.run_sync_in_worker_thread function in trio

To help you get started, we’ve selected a few trio examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github s3ql / s3ql / tests / t2_block_cache.py View on Github external
async def send(self, arg):
                await trio.run_sync_in_worker_thread(cache._do_upload, *arg)
        cache.to_upload = (DummyChannel(), None)
github python-voca / voca / tests / helpers.py View on Github external
async def async_capture_keypresses():
    captured = []

    def capture(event):
        if event.event == sneakysnek.keyboard_event.KeyboardEvents.DOWN:
            captured.append(event.keyboard_key.name)

    rec = await trio.run_sync_in_worker_thread(sneakysnek.recorder.Recorder.record, capture)
    yield captured
    rec.stop()
github codypiersall / pynng / examples / pair1_async.py View on Github external
the listening process.  Whatever you type into the listening process is sent to
*all* the dialing processes.

"""

import argparse

import pynng
import trio


try:
    run_sync = trio.to_thread.run_sync
except AttributeError:
    # versions of trio prior to 0.12.0 used this method
    run_sync = trio.run_sync_in_worker_thread


async def send_eternally(sock):
    """
    Eternally listen for user input in the terminal and send it on all
    available pipes.
    """
    while True:
        stuff = await run_sync(input, cancellable=True)
        for pipe in sock.pipes:
            await pipe.asend(stuff.encode())


async def recv_eternally(sock):
    while True:
        msg = await sock.arecv_msg()
github HyperionGray / starbelly / starbelly / login.py View on Github external
substituting the provided ``username`` and ``password`` into the
        corresponding fields. Returns the data needed to POST a login request.

        :param starbelly.downloader.DownloadResponse response:
        :param str username: The username to log in with.
        :param str password: The password to log in with.
        :returns: (action, method, fields)
        :rtype: tuple
        '''
        _, html = w3lib.encoding.html_to_unicode(
            response.content_type,
            response.body,
            auto_detect_fun=chardet
        )

        forms = await trio.run_sync_in_worker_thread(partial(
            formasaurus.extract_forms, html, proba=True))
        form, meta = select_login_form(forms)

        if form is None:
            raise Exception("Can't find login form")

        login_field, password_field, captcha_field = select_login_fields(
            meta['fields'])
        if login_field is None or password_field is None:
            raise Exception("Can't find username/password fields")

        form.fields[login_field] = username
        form.fields[password_field] = password

        if captcha_field is not None:
            if self._policy.captcha_solver is None:
github HyperionGray / starbelly / starbelly / extractor.py View on Github external
async def _extract(self, response):
        '''
        Find links in a response body and put them in the frontier.

        :param starbelly.downloader.DownloadReponse:
        '''
        logger.debug('%r Extracting links from %s', self, response.url)
        extracted_urls = await trio.run_sync_in_worker_thread(
            extract_urls, response)
        insert_items = list()

        for counter, url in enumerate(extracted_urls):
            # Check if the policy allows us to follow this URL.
            new_cost = self._policy.url_rules.get_cost(response.cost, url)
            exceeds_max_cost = self._policy.limits.exceeds_max_cost(new_cost)
            if new_cost <= 0 or exceeds_max_cost:
                continue
            robots_ok = await self._robots_txt_manager.is_allowed(url,
                self._policy, self._downloader)
            if not robots_ok:
                continue

            # Normalize and hash URL.
            url_can = self._policy.url_normalization.normalize(url)
github s3ql / s3ql / src / s3ql / mount.py View on Github external
with self.backend_pool() as backend:
                seq_no = get_seq_no(backend)
                if seq_no > self.param['seq_no']:
                    log.error('Remote metadata is newer than local (%d vs %d), '
                              'refusing to overwrite and switching to failsafe mode!',
                              seq_no, self.param['seq_no'])
                    self.fs.failsafe = True
                    fh.close()
                    break

                fh.seek(0)
                self.param['last-modified'] = time.time()

                # Temporarily decrease sequence no, this is not the final upload
                self.param['seq_no'] -= 1
                await trio.run_sync_in_worker_thread(
                    upload_metadata, backend, fh, self.param)
                self.param['seq_no'] += 1

                fh.close()
                self.db_mtime = new_mtime

        # Break reference loop
        self.fs = None

        log.debug('finished')
github Fuyukai / curious / curious / core / _ws_wrapper / trio_wrapper.py View on Github external
async def open(cls, url: str, nursery) -> "BasicWebsocketWrapper":
        """
        Opens a new websocket connection.

        :param url: The URL to use.
        :param nursery: The nursery to use.
        """
        obb = cls(url, nursery)
        partial = functools.partial(trio.run_sync_in_worker_thread)
        nursery.start_soon(partial, obb.websocket_task)
        return obb
github s3ql / s3ql / src / s3ql / block_cache.py View on Github external
return False

            log.debug('uploading %s..', el)
            self.in_transit.add(el)
            added_to_transit = True
            sha = hashlib.sha256()
            el.seek(0)

            def with_lock_released():
                while True:
                    buf = el.read(BUFSIZE)
                    if not buf:
                        break
                    sha.update(buf)
                return sha.digest()
            hash_ = await trio.run_sync_in_worker_thread(with_lock_released)

        except:
            if added_to_transit:
                self.in_transit.discard(el)
            await self.mlock.release(el.inode, el.blockno)
            raise

        obj_lock_taken = False
        try:
            try:
                old_block_id = self.db.get_val('SELECT block_id FROM inode_blocks '
                                               'WHERE inode=? AND blockno=?',
                                               (el.inode, el.blockno))
            except NoSuchRowError:
                old_block_id = None
github python-voca / voca / src / voca / plugins / basic.py View on Github external
async def write(message: str):
    """Type the ``message``."""
    await trio.run_sync_in_worker_thread(
        functools.partial(pyautogui.typewrite, message)
    )