Python time.sleep() Examples

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

Example 1
Project: unicorn-hat-hd   Author: pimoroni   File: weather-icons.py    MIT License 10 votes vote down vote up
def draw_animation(image):
    # this is the original pimoroni function for drawing sprites
    try:

        for o_x in range(int(image.size[0] / width)):

            for o_y in range(int(image.size[1] / height)):

                valid = False

                for x in range(width):

                    for y in range(height):
                        pixel = image.getpixel(((o_x * width) + y, (o_y * height) + x))
                        r, g, b = int(pixel[0]), int(pixel[1]), int(pixel[2])
                        if r or g or b:
                            valid = True
                        unicorn.set_pixel(x, y, r, g, b)

                if valid:
                    unicorn.show()
                    time.sleep(cycle_time)

    except KeyboardInterrupt:
        unicorn.off() 
Example 2
Project: unicorn-hat-hd   Author: pimoroni   File: __init__.py    MIT License 6 votes vote down vote up
def show():
    """Output the contents of the buffer to Unicorn HAT HD."""
    setup()
    if _addressing_enabled:
        for address in range(8):
            display = _displays[address]
            if display.enabled:
                if _buffer_width == _buffer_height or _rotation in [0, 2]:
                    window = display.get_buffer_window(numpy.rot90(_buf, _rotation))
                else:
                    window = display.get_buffer_window(numpy.rot90(_buf, _rotation))

                _spi.xfer2([_SOF + 1 + address] + (window.reshape(768) * _brightness).astype(numpy.uint8).tolist())
                time.sleep(_DELAY)
    else:
        _spi.xfer2([_SOF] + (numpy.rot90(_buf, _rotation).reshape(768) * _brightness).astype(numpy.uint8).tolist())

    time.sleep(_DELAY) 
Example 3
Project: NordVPN-NetworkManager-Gui   Author: vfosterm   File: nord_nm_gui.py    GNU General Public License v3.0 6 votes vote down vote up
def disconnect_vpn(self):
        """
        Steps through all of the UI logic to disconnect VPN
        """
        if self.killswitch_btn.isChecked():
            self.killswitch_btn.setChecked(False)
            self.statusbar.showMessage("Disabling Killswitch...", 5000)
            self.repaint()
            self.disable_kill_switch()
            time.sleep(5)  # sleep time to mitigate NetworkManager still killing connection
        if self.auto_connect_box.isChecked():
            self.auto_connect_box.setChecked(False)
            self.statusbar.showMessage("Disabling auto-connect...", 1000)
            self.disable_auto_connect()
        self.disable_connection()
        self.remove_connection()
        self.enable_ipv6()
        self.statusbar.clearMessage()
        self.repaint()

        # UI changes here
        self.disconnect_btn.hide()
        self.connect_btn.show()
        self.retranslateUi() 
Example 4
Project: fs_image   Author: facebookincubator   File: test_unshare.py    MIT License 6 votes vote down vote up
def _popen_sleep_forever(self, unshare: Unshare):
        # We need the ready signal to know when we've actually executed the
        # payload -- otherwise, we might try to interact with it while we're
        # still at `nsenter`.
        proc = subprocess.Popen(nsenter_as_user(
            unshare, 'bash', '-uec', 'echo ready $$ ; exec sleep infinity',
        ), stdout=subprocess.PIPE)

        # Wait for the child to start
        ready_and_pid = proc.stdout.readline().split(b' ')
        self.assertEqual(b'ready', ready_and_pid[0])

        proc.stdout.close()  # `sudo` keeps stdout open, but will not write.
        # Returning the PID lets us clean up the `sleep infinity` when it is
        # not inside a PID namespace.
        return proc, int(ready_and_pid[1]) 
Example 5
Project: fs_image   Author: facebookincubator   File: test_unshare.py    MIT License 6 votes vote down vote up
def test_pid_namespace_dead_keepalive(self):
        with Unshare([Namespace.PID]) as unshare:
            self._check_ns_diff(unshare, {'pid'})

            good_echo = nsenter_as_user(unshare, 'echo')
            subprocess.check_call(good_echo)  # Will fail once the NS is dead

            proc, _ = self._popen_sleep_forever(unshare)
            time.sleep(2)  # Leave some time for `sleep` to exit erroneously
            self.assertEqual(None, proc.poll())  # Sleeps forever

            self._kill_keepalive(unshare)

            self.assertEqual(-signal.SIGKILL, proc.wait())  # The NS is dead

            # The `echo` command that worked above no longer works.
            with self.assertRaises(subprocess.CalledProcessError):
                subprocess.check_call(good_echo) 
Example 6
Project: Home_Surveillance_with_Python   Author: kalfasyan   File: base_camera.py    MIT License 6 votes vote down vote up
def _thread(cls):
        """Camera background thread."""
        print('Starting camera thread.')
        frames_iterator = cls.frames()
        for frame in frames_iterator:
            BaseCamera.frame = frame
            BaseCamera.event.set()  # send signal to clients
            time.sleep(0)

            # if there hasn't been any clients asking for frames in
            # the last 10 seconds then stop the thread
            if time.time() - BaseCamera.last_access > 10*60*500:
                frames_iterator.close()
                print('Stopping camera thread due to inactivity.')
                break
        BaseCamera.thread = None 
Example 7
Project: http2mqtt   Author: chris-gunawardena   File: chip_neopixels.py    MIT License 6 votes vote down vote up
def off():
  neo.clear()

# def on():
#   for i in range(255):
#     for Led in neo.Leds:
#       Led.set(0,0,0,i)
#     time.sleep(0.001)
#     neo.refresh()

# def off():
#   for i in range(255):
#     for Led in neo.Leds:
#       Led.set(255-i,255-i,255-i,255-i)
#     time.sleep(0.001)
#     neo.refresh() 
Example 8
Project: incubator-spot   Author: apache   File: collector.py    Apache License 2.0 6 votes vote down vote up
def start(self):

        self._logger.info("Starting FLOW ingest") 
        self._watcher.start()
            
        try:
            while True:                
                self._ingest_files_pool()              
                time.sleep(self._ingestion_interval)
        except KeyboardInterrupt:
            self._logger.info("Stopping FLOW collector...")  
            Util.remove_kafka_topic(self._producer.Zookeeper, self._producer.Topic, self._logger)
            self._watcher.stop()
            self._pool.terminate()
            self._pool.close()            
            self._pool.join()
            SystemExit("Ingest finished...") 
Example 9
Project: incubator-spot   Author: apache   File: collector.py    Apache License 2.0 6 votes vote down vote up
def start(self):

        self._logger.info("Starting PROXY collector")
        self._watcher.start()   
    
        try:
            while True:
                #self._ingest_files()
                self._ingest_files_pool()              
                time.sleep(self._ingestion_interval)
        except KeyboardInterrupt:
            self._logger.info("Stopping Proxy collector...")  
            Util.remove_kafka_topic(self._kafka_topic.Zookeeper,self._kafka_topic.Topic,self._logger)          
            self._watcher.stop()
            self._pool.terminate()
            self._pool.close()            
            self._pool.join() 
Example 10
Project: incubator-spot   Author: apache   File: collector.py    Apache License 2.0 6 votes vote down vote up
def start(self):

        self._logger.info("Starting DNS ingest")
        self._watcher.start()

        try:
            while True:
                self._ingest_files_pool()
                time.sleep(self._ingestion_interval)
        except KeyboardInterrupt:
            self._logger.info("Stopping DNS collector...")
            Util.remove_kafka_topic(self._producer.Zookeeper, self._producer.Topic, self._logger)
            self._watcher.stop()
            self._pool.terminate()
            self._pool.close()
            self._pool.join()
            SystemExit("Ingest finished...") 
Example 11
Project: AboveTustin   Author: kevinabrandon   File: screenshot.py    MIT License 6 votes vote down vote up
def clickOnAirplane(self, text):
        '''
        clickOnAirplane()
        Clicks on the airplane with the name text, and then takes a screenshot
        '''
        try:
            element = self.browser.find_elements_by_xpath("//td[text()='%s']" % text.lower())
            print("number of elements found: %i" % len(element))
            if len(element) > 0:
                print("clicking on {}!".format(text))
                element[0].click()
                time.sleep(0.5) # if we don't wait a little bit the airplane icon isn't drawn.
                return self.screenshot('tweet.png')
            else:
                print("couldn't find the object")
        except Exception as e:
            util.error("Could not click on airplane: {}".format(e))
            return None 
Example 12
Project: AboveTustin   Author: kevinabrandon   File: screenshot.py    MIT License 6 votes vote down vote up
def clickOnAirplane(self, text):
        '''
        clickOnAirplane()
        Clicks on the airplane with the name text, and then takes a screenshot
        '''
        try:
            aircraft = self.browser.find_element_by_xpath("//td[text()='%s']" % text)
            aircraft.click()
            time.sleep(0.5) # if we don't wait a little bit the airplane icon isn't drawn.
            show_on_map = self.browser.find_element_by_link_text('Show on map')
            show_on_map.click()
            time.sleep(3.0)
            return self.screenshot('tweet.png')
        except Exception as e:
            util.error("Unable to click on airplane: {}'".format(e))
            return None 
Example 13
Project: kicker-module   Author: EvanTheB   File: backend.py    GNU General Public License v3.0 6 votes vote down vote up
def test_concurrent():
    # run this in multiple processes,
    # the idea is that collisions will crash, but not munge data
    import random
    import time
    if not os.path.exists("tmp_test_con.log"):
        init_data_file("tmp_test_con.log")

    k = LadderData("tmp_test_con.log")
    # test concurrent log writes
    thread = str(random.randint(0, 100))
    print thread
    for x in range(100):
        time.sleep(0.01)
        k.add_player(thread + '_' + str(x))

    p, g = k.get_players_games()
    print len(p) 
Example 14
Project: webnull   Author: macrael   File: test_integration.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run_test_command(self, cmd):
        observer = FSEventsObserver()
        shared_queue = Queue.Queue()
        handler = ChangeHandler(shared_queue)
        observer.schedule(handler, self.temp_dir)
        observer.start()

        args = ['./webnull.py'] + cmd
        env = os.environ.copy()
        if 'DEV_MODE' in env:
            del env['DEV_MODE']
        env['HOSTFILE_PATH'] = self.hostfile_path
        env['TEST_DURATION'] = '0.02'
        process = subprocess.Popen(args, env=env)
        process.wait()
        time.sleep(.09) # if we just quit, the observer doesn't see the final file action.

        bodies = []
        while not shared_queue.empty():
            bodies.append(shared_queue.get())

        observer.stop()
        observer.join()
        return bodies 
Example 15
Project: tom-bot   Author: maartenberg   File: layer.py    MIT License 6 votes vote down vote up
def onEvent(self, layerEvent):
        ''' Handles disconnection events and reconnects if we timed out.'''
        # pylint: disable=invalid-name
        logging.debug('Event %s received', layerEvent.getName())
        if layerEvent.getName() == YowNetworkLayer.EVENT_STATE_DISCONNECTED:
            reason = layerEvent.getArg('reason')
            logging.warning(_('Connection lost: {}').format(reason))
            registry.fire_event(registry.BOT_DISCONNECTED, self)
            if reason == 'Connection Closed':
                time.sleep(.5)
                logging.warning(_('Reconnecting'))
                self.getStack().broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))
                self.connected = False
                return True
            else:
                logging.error('Fatal disconnect: %s', reason)
                if self.connected and reason != 'Requested':
                    self.stop()
                return False
        elif layerEvent.getName() == YowNetworkLayer.EVENT_STATE_CONNECTED:
            logging.info('Connection established.')
            self.connected = True
            self.set_online()
            registry.fire_event(registry.BOT_CONNECTED, self)
        return False 
Example 16
Project: pepper-robot-programming   Author: maverickjoy   File: human_greeter.py    MIT License 6 votes vote down vote up
def run(self):
        """
        Loop on, wait for events until manual interruption.
        """
        # start
        print "Waiting for the robot to be in wake up position"
        self.motion.wakeUp()

        print "Starting HumanGreeter"
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            print "Interrupted by user, stopping HumanGreeter"
            self.face_detection.unsubscribe("HumanGreeter")
            #stop
            sys.exit(0)

        return 
Example 17
Project: pepper-robot-programming   Author: maverickjoy   File: asthama_search.py    MIT License 6 votes vote down vote up
def _startImageCapturingAtGraphNode(self):
        amntY = 0.3
        xdir = [-0.5, 0, 0.5]
        cameraId = 0

        for idx,amntX in enumerate(xdir):
            self._moveHead(amntX, amntY)
            time.sleep(0.1)
            self._checkIfAsthamaInEnvironment(cameraId)
            if self.pumpFound :
                # Setting rotation angle of body towards head
                theta = 0
                if idx == 0: # LEFT
                    theta = math.radians(-45)
                if idx == 2: # RIGHT
                    theta = math.radians(45)
                self.pumpAngleRotation = theta

                return "KILLING GRAPH SEARCH : PUMP FOUND"

        self._moveHead(0, 0) # Bringing to initial view

        return 
Example 18
Project: pyblish-win   Author: pyblish   File: test_io.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_threads_write(self):
        # Issue6750: concurrent writes could duplicate data
        event = threading.Event()
        with self.open(support.TESTFN, "w", buffering=1) as f:
            def run(n):
                text = "Thread%03d\n" % n
                event.wait()
                f.write(text)
            threads = [threading.Thread(target=lambda n=x: run(n))
                       for x in range(20)]
            for t in threads:
                t.start()
            time.sleep(0.02)
            event.set()
            for t in threads:
                t.join()
        with self.open(support.TESTFN) as f:
            content = f.read()
            for n in range(20):
                self.assertEqual(content.count("Thread%03d\n" % n), 1) 
Example 19
Project: pyblish-win   Author: pyblish   File: test_threading.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_join_nondaemon_on_shutdown(self):
        # Issue 1722344
        # Raising SystemExit skipped threading._shutdown
        p = subprocess.Popen([sys.executable, "-c", """if 1:
                import threading
                from time import sleep

                def child():
                    sleep(1)
                    # As a non-daemon thread we SHOULD wake up and nothing
                    # should be torn down yet
                    print "Woke up, sleep function is:", sleep

                threading.Thread(target=child).start()
                raise SystemExit
            """],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE)
        self.addCleanup(p.stdout.close)
        self.addCleanup(p.stderr.close)
        stdout, stderr = p.communicate()
        self.assertEqual(stdout.strip(),
            "Woke up, sleep function is: <built-in function sleep>")
        stderr = re.sub(r"^\[\d+ refs\]", "", stderr, re.MULTILINE).strip()
        self.assertEqual(stderr, "") 
Example 20
Project: pyblish-win   Author: pyblish   File: test_threading.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_dummy_thread_after_fork(self):
        # Issue #14308: a dummy thread in the active list doesn't mess up
        # the after-fork mechanism.
        code = """if 1:
            import thread, threading, os, time

            def background_thread(evt):
                # Creates and registers the _DummyThread instance
                threading.current_thread()
                evt.set()
                time.sleep(10)

            evt = threading.Event()
            thread.start_new_thread(background_thread, (evt,))
            evt.wait()
            assert threading.active_count() == 2, threading.active_count()
            if os.fork() == 0:
                assert threading.active_count() == 1, threading.active_count()
                os._exit(0)
            else:
                os.wait()
        """
        _, out, err = assert_python_ok("-c", code)
        self.assertEqual(out, '')
        self.assertEqual(err, '') 
Example 21
Project: unicorn-hat-hd   Author: pimoroni   File: show_my_ip.py    MIT License 5 votes vote down vote up
def scroll_txt(image, text_width):
    unicornhathd.rotation(0)
    for scroll in range(text_width - width):
        for x in range(width):
            for y in range(height):
                pixel = image.getpixel((x + scroll, y))
                r, g, b = [int(n) for n in pixel]
                unicornhathd.set_pixel(width - 1 - x, y, r, g, b)
        unicornhathd.show()
        time.sleep(0.02)
    unicornhathd.off()


# one stop call for scrolling text 
Example 22
Project: UrsaRobotics_SmartHome   Author: stav98   File: speech_recogn.py    GNU General Public License v3.0 5 votes vote down vote up
def wait_for_message(d):
    client.loop_start()
    time.sleep(d)
    client.loop_stop()

#Για πάντα 
Example 23
Project: factotum   Author: Denubis   File: factotum.py    GNU General Public License v3.0 5 votes vote down vote up
def stop():
	"""Shortcut for factorio stop."""
	try:
		FACTORIOPATH = getFactorioPath()
		with open('/tmp/factorio.pid', 'r') as pidfile:
			pid = int(pidfile.read().strip())
			os.kill(pid, signal.SIGINT)
		print("SIGINT sent")
		time.sleep(10)
	except FileNotFoundError:
		print("Cannot find pid. Factorio has not been started.")		
	print(subprocess.check_output(['tail', '-13', '%s/factorio-current.log'%FACTORIOPATH]).decode("unicode_escape")) 
Example 24
Project: fs_image   Author: facebookincubator   File: common.py    MIT License 5 votes vote down vote up
def retry_fn(
    fn: Callable[[], T], *, delays: List[float] = None, what: str,
) -> T:
    'Delays are in seconds.'
    for i, delay in enumerate(delays):
        try:
            return fn()
        except Exception:
            log.exception(
                f'\n\n[Retry {i + 1} of {len(delays)}] {what} -- waiting '
                f'{delay} seconds.\n\n'
            )
            time.sleep(delay)
    return fn()  # With 0 retries, we should still run the function. 
Example 25
Project: fs_image   Author: facebookincubator   File: test_unshare.py    MIT License 5 votes vote down vote up
def test_pid_namespace(self):
        with Unshare([Namespace.PID]) as unshare:
            proc, _ = self._popen_sleep_forever(unshare)
            # Check that "as user" works.
            for arg, expected in (('-u', os.geteuid()), ('-g', os.getegid())):
                actual = int(subprocess.check_output(nsenter_as_user(
                    unshare, 'id', arg
                )))
                self.assertEqual(expected, actual)
            time.sleep(2)  # Leave some time for `sleep` to exit erroneously
            self.assertEqual(None, proc.poll())  # Sleeps forever

            self._check_ns_diff(unshare, {'pid'})

        self.assertEqual(-signal.SIGKILL, proc.poll())  # Reaped by PID NS 
Example 26
Project: leapp-repository   Author: oamg   File: rhsm.py    Apache License 2.0 5 votes vote down vote up
def _rhsm_retry(max_attempts, sleep=None):
    """
    A decorator to retry executing a function/method if unsuccessful.

    The function/method execution is considered unsuccessful when it raises StopActorExecutionError.

    :param max_attempts: Maximum number of attempts to execute the decorated function/method.
    :param sleep: Time to wait between attempts. In seconds.
    """
    def impl(f):
        @functools.wraps(f)
        def wrapper(*args, **kwargs):
            attempts = 0
            while True:
                attempts += 1
                try:
                    return f(*args, **kwargs)
                except StopActorExecutionError:
                    if max_attempts <= attempts:
                        api.current_logger().warning(
                            'Attempt %d of %d to perform %s failed. Maximum number of retries has been reached.',
                            attempts, max_attempts, f.__name__)
                        raise
                    if sleep:
                        api.current_logger().info(
                            'Attempt %d of %d to perform %s failed - Retrying after %s seconds',
                            attempts, max_attempts, f.__name__, str(sleep))
                        time.sleep(sleep)
                    else:
                        api.current_logger().info(
                            'Attempt %d of %d to perform %s failed - Retrying...', attempts, max_attempts, f.__name__)
        return wrapper
    return impl 
Example 27
Project: Home_Surveillance_with_Python   Author: kalfasyan   File: base_camera.py    MIT License 5 votes vote down vote up
def __init__(self):
        """Start the background camera thread if it isn't running yet."""
        if BaseCamera.thread is None:
            BaseCamera.last_access = time.time()

            # start background frame thread
            BaseCamera.thread = threading.Thread(target=self._thread)
            BaseCamera.thread.start()

            # wait until frames are available
            while self.get_frame() is None:
                time.sleep(0) 
Example 28
Project: Home_Surveillance_with_Python   Author: kalfasyan   File: camera.py    MIT License 5 votes vote down vote up
def frames():
        while True:
            time.sleep(1)
            yield Camera.imgs[int(time.time()) % 3] 
Example 29
Project: 21tb_robot   Author: iloghyr   File: study_robot.py    MIT License 5 votes vote down vote up
def study(self, course_id):
        """study one course"""
        time_step = 180
        log('start course:%s' % course_id)
        self.http.post(self.apis['enter_course'] % course_id, json_ret=False)
        course_show_api = self.apis['course_show'] % course_id
        log('url:%s' % course_show_api)
        self.http.post(course_show_api, json_ret=False)
        items_list = self.get_course_items(course_id)
        log('*' * 50)
        log('共有 %s 个子课程' % len(items_list))
        for index, i in enumerate(items_list):
            log('%s、%s ' % (index + 1, i['name']))
        log('*' * 50)
        log('begin to start...')
        for index, i in enumerate(items_list):
            sco_id = i['scoId']
            log('begin to study:%s-%s %s' % (index + 1, i['name'], sco_id))
            location = self.select_score_item(course_id, sco_id)
            cnt = 0
            while True:
                location = location + time_step * cnt
                cnt += 1
                log('location: %s' % location)
                self.do_heartbeat()
                self.update_timestep()
                ret = self.do_save(course_id, sco_id, location)
                if ret:
                    log('%s-%s %s' % (course_id, sco_id, 'done, start next'))
                    break
                log('*********** study %ss then go on *************' % time_step)
                time.sleep(time_step)
        info = '\033[92m\tDONE COURSE, url:%s\033[0m' % course_show_api
        log(info) 
Example 30
Project: incubator-spot   Author: apache   File: collector.py    Apache License 2.0 5 votes vote down vote up
def isalive(self):
        '''
            Wait and return True if instance is still alive.
        '''
        time.sleep(self._interval)
        return self._isalive 
Example 31
Project: jumpserver-python-sdk   Author: jumpserver   File: service.py    GNU General Public License v2.0 5 votes vote down vote up
def valid_auth(self):
        delay = 1
        while delay < 100:
            user = self.get_profile()
            if not user:
                msg = "Connect server error or access key is invalid, " \
                      "remove `./data/keys/.access_key` run again"
                logger.error(msg)
                delay += 3
                time.sleep(3)
            else:
                break
        if delay >= 10:
            sys.exit() 
Example 32
Project: clikit   Author: sdispater   File: progress_indicator.py    MIT License 5 votes vote down vote up
def _spin(self):
        while not self._auto_running.is_set():
            self.advance()

            time.sleep(0.1) 
Example 33
Project: BlueLightMeter   Author: chripell   File: as726x.py    Apache License 2.0 5 votes vote down vote up
def soft_reset(self):
        value = self.read_reg(self.CONTROL_SETUP)
        value |= (1 << 7)
        self.write_reg(self.CONTROL_SETUP, value)
        time.sleep(1)

    # Reset must be wired to Buspirate CS 
Example 34
Project: BlueLightMeter   Author: chripell   File: as726x.py    Apache License 2.0 5 votes vote down vote up
def hard_reset(self):
        self.i2c.set_pin(0, 0)
        time.sleep(1)
        self.i2c.set_pin(1, 1)
        time.sleep(1)

    # Mode 0: Continuous reading of VBGY (7262) / STUV (7263)
    # Mode 1: Continuous reading of GYOR (7262) / RTUX (7263)
    # Mode 2: Continuous reading of all channels (power-on default)
    # Mode 3: One-shot reading of all channels 
Example 35
Project: webnull   Author: macrael   File: webnull.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def reblock_timer(duration, cleanup_func):
    if 'TEST_DURATION' in os.environ:
        duration = float(os.environ['TEST_DURATION'])

    def sigint_handler(signal, frame):
        cleanup_func()
        sys.exit(0)
    signals = [signal.SIGINT, signal.SIGHUP]
    for sig in signals:
        signal.signal(sig, sigint_handler)

    end_time = datetime.datetime.now() + datetime.timedelta(minutes=duration)
    ptime = pretty_time(end_time)
    print('allowed until ' + ptime)

    now = time.time()
    end_time = now + (duration * 60)
    while True:
        remaining = end_time - time.time()
        if remaining <= 0:
            break
        if remaining > 1000:
            time.sleep(10)
        else:
            time.sleep(1)

    cleanup_func() 
Example 36
Project: tom-bot   Author: maartenberg   File: layer.py    MIT License 5 votes vote down vote up
def onMessage(self, message):
        ''' Handles incoming messages and responds to them if needed. '''
        # pylint: disable=invalid-name
        logging.debug('Message %s from %s received, content: %s',
                      message.getId(), message.getFrom(), message.getBody())

        receipt = OutgoingReceiptProtocolEntity(
            message.getId(), message.getFrom(),
            'read', message.getParticipant())
        self.toLower(receipt)

        time.sleep(0.2)
        self.react(message)

        registry.fire_event(registry.BOT_MSG_RECEIVE, self, message) 
Example 37
Project: apm-python-agent-principle   Author: mozillazg   File: hello.py    MIT License 5 votes vote down vote up
def sleep(n):
    time.sleep(n)
    return n 
Example 38
Project: apm-python-agent-principle   Author: mozillazg   File: func_wrapper.py    MIT License 5 votes vote down vote up
def sleep(n):
    time.sleep(n)
    return n 
Example 39
Project: apm-python-agent-principle   Author: mozillazg   File: hello.py    MIT License 5 votes vote down vote up
def sleep(n):
    time.sleep(n)
    return n 
Example 40
Project: apm-python-agent-principle   Author: mozillazg   File: hello.py    MIT License 5 votes vote down vote up
def sleep(n):
    time.sleep(n)
    return n 
Example 41
Project: pepper-robot-programming   Author: maverickjoy   File: human_greeter_with_awareness.py    MIT License 5 votes vote down vote up
def run(self):
        """
            this example uses the setEngagementMode, startAwareness and
            stopAwareness methods
        """
        # start
        print "Waiting for the robot to be in wake up position"
        self.motion.wakeUp()

        self.create_callbacks()

        print "Starting BasicAwareness with the fully engaged mode"
        self.basic_awareness.setEngagementMode("FullyEngaged")
        self.basic_awareness.setEnabled(True)

        # loop on, wait for events until manual interruption
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            print "Interrupted by user, shutting down"
            # stop
            print "Stopping BasicAwareness"
            self.basic_awareness.setEnabled(False)

            print "Waiting for the robot to be in rest position"
            self.motion.rest()

            sys.exit(0)

        return 
Example 42
Project: pepper-robot-programming   Author: maverickjoy   File: human_greeter.py    MIT License 5 votes vote down vote up
def on_human_tracked(self, value):
        """
        Callback for event FaceDetected.
        """
        if value == []:  # empty value when the face disappears
            self.got_face = False
        elif not self.got_face:  # only speak the first time a face appears
            self.got_face = True
            print "I saw a face!"
            self.tts.say("Hello Human !")
            # First Field = TimeStamp.
            timeStamp = value[0]
            print "TimeStamp is: " + str(timeStamp)

            # Second Field = array of face_Info's.
            faceInfoArray = value[1]
            for j in range( len(faceInfoArray)-1 ):
                faceInfo = faceInfoArray[j]

                # First Field = Shape info.
                faceShapeInfo = faceInfo[0]

                # Second Field = Extra info (empty for now).
                faceExtraInfo = faceInfo[1]

                print "Face Infos :  alpha %.3f - beta %.3f" % (faceShapeInfo[1], faceShapeInfo[2])
                print "Face Infos :  width %.3f - height %.3f" % (faceShapeInfo[3], faceShapeInfo[4])
                print "Face Extra Infos :" + str(faceExtraInfo)

            # Waiting for a buffer time so that it is not very quick and confusing.
            time.sleep(3)

        return 
Example 43
Project: pepper-robot-programming   Author: maverickjoy   File: asthama_search.py    MIT License 5 votes vote down vote up
def search_asthama_pump_event(self, value):
        self._printLogs("Searching Asthama Pump : " + str(value), "NORMAL")
        try:
            self.startAsthamaPumpSearch()
        except KeyboardInterrupt:
            self._printLogs("KeyBoard Interrupt initiated", "FAIL")
            self.motion_service.stopMove()
            return

        time.sleep(1)

        return 
Example 44
Project: pepper-robot-programming   Author: maverickjoy   File: asthama_search.py    MIT License 5 votes vote down vote up
def capture_image_event(self, value):
        self._printLogs("Capturing Image : " + str(value), "NORMAL")

        if str(value) == "2d":
            cameraId = 0 # DEFAULT TOP
            self._capture2dImage(cameraId)

        if str(value) == "3d":
            self._capture3dImage()

        time.sleep(1)
        return 
Example 45
Project: pepper-robot-programming   Author: maverickjoy   File: asthama_search.py    MIT License 5 votes vote down vote up
def run(self):
        self._printLogs("Waiting for the robot to be in wake up position", "OKBLUE")

        self.motion_service.wakeUp()
        self.posture_service.goToPosture("StandInit", 0.1)

        self.create_callbacks()
        # self.startDLServer()
        self._addTopic()

        # graphplots
        self._initialisePlot()
        ani = animation.FuncAnimation(self.fig, self._animate, blit=False, interval=500 ,repeat=False)


        # loop on, wait for events until manual interruption
        try:
            # while True:
            #     time.sleep(1)
            # starting graph plot
            plt.show() # blocking call hence no need for while(True)

        except KeyboardInterrupt:
            self._printLogs("Interrupted by user, shutting down", "FAIL")
            self._cleanUp()

            self._printLogs("Waiting for the robot to be in rest position", "FAIL")
            # self.motion_service.rest()
            sys.exit(0)

        return 
Example 46
Project: pepper-robot-programming   Author: maverickjoy   File: remote_voice.py    MIT License 5 votes vote down vote up
def capture_image_event(self, value):

        print "Capturing Image : " + str(value)

        if str(value) == "2d":
            cameraId = 0 # DEFAULT TOP
            self._capture2dImage(cameraId)

        if str(value) == "3d":
            self._capture3dImage()

        time.sleep(1)
        return 
Example 47
Project: pepper-robot-programming   Author: maverickjoy   File: remote_voice.py    MIT License 5 votes vote down vote up
def run(self):
        # start
        print "Waiting for the robot to be in wake up position"
        self.motion.wakeUp()
        self.posture_service.goToPosture("StandInit", 0.5)

        self.create_callbacks()
        self.addTopic()


        # loop on, wait for events until manual interruption
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            print "Interrupted by user, shutting down"

            print "Starting Clean Up process"
            self.cleanUp()

            print "Waiting for the robot to be in rest position"
            self.motion.rest()

            sys.exit(0)

        return 
Example 48
Project: pepper-robot-programming   Author: maverickjoy   File: remote_terminal.py    MIT License 5 votes vote down vote up
def _rotateHead(self):

        JointNamesH = ["HeadPitch", "HeadYaw"] # range ([-1,1],[-0.5,0.5]) // HeadPitch :{(-)up,(+)down} , HeadYaw :{(-)left,(+)right}

        amntY =  raw_input("Enter amount to Move Up(-) And Down(+) [-1,1] : ")
        amntX =  raw_input("Enter amount to Move Left(-) And Right(+) [-0.5,0.5] : ")

        pFractionMaxSpeed = 0.2

        HeadA = [float(amntY),float(amntX)]

        self.motion_service.angleInterpolationWithSpeed(JointNamesH, HeadA, pFractionMaxSpeed)
        time.sleep(1)

        return 
Example 49
Project: pyblish-win   Author: pyblish   File: wsgui.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def mainloop(self):
        while not self.done:
            time.sleep(0.1)
            self.top.update() 
Example 50
Project: pyblish-win   Author: pyblish   File: audiodev.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def wait(self):
        if not self.port:
            return
        import time
        while self.port.getfilled() > 0:
            time.sleep(0.1)
        self.stop() 
Example 51
Project: pyblish-win   Author: pyblish   File: test_thread.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def deadlockThread(self):
        self.doLockDetect = True
        while self.doLockDetect:
            time.sleep(0.05)
            try:
                aborted = self.env.lock_detect(
                    db.DB_LOCK_RANDOM, db.DB_LOCK_CONFLICT)
                if verbose and aborted:
                    print "deadlock: Aborted %d deadlocked transaction(s)" \
                          % aborted
            except db.DBError:
                pass 
Example 52
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _testClose(self):
        self.cli.connect((HOST, self.port))
        time.sleep(1.0) 
Example 53
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _testAccept(self):
        time.sleep(0.1)
        self.cli.connect((HOST, self.port)) 
Example 54
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _testRecv(self):
        self.cli.connect((HOST, self.port))
        time.sleep(0.1)
        self.cli.send(MSG) 
Example 55
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testInsideTimeout(self):
        conn, addr = self.serv.accept()
        self.addCleanup(conn.close)
        time.sleep(3)
        conn.send("done!") 
Example 56
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def clientSetUp(self):
        # The is a hittable race between serverExplicitReady() and the
        # accept() call; sleep a little while to avoid it, otherwise
        # we could get an exception
        time.sleep(0.1)
        self.cli = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
        addr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
                TIPC_LOWER + (TIPC_UPPER - TIPC_LOWER) / 2, 0)
        self.cli.connect(addr)
        self.cliaddr = self.cli.getsockname() 
Example 57
Project: pyblish-win   Author: pyblish   File: test_wait3.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def wait_impl(self, cpid):
        for i in range(10):
            # wait3() shouldn't hang, but some of the buildbots seem to hang
            # in the forking tests.  This is an attempt to fix the problem.
            spid, status, rusage = os.wait3(os.WNOHANG)
            if spid == cpid:
                break
            time.sleep(1.0)

        self.assertEqual(spid, cpid)
        self.assertEqual(status, 0, "cause = %d, exit = %d" % (status&0xff, status>>8))
        self.assertTrue(rusage) 
Example 58
Project: pyblish-win   Author: pyblish   File: test_io.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_threads(self):
        try:
            # Write out many bytes with exactly the same number of 0's,
            # 1's... 255's. This will help us check that concurrent reading
            # doesn't duplicate or forget contents.
            N = 1000
            l = list(range(256)) * N
            random.shuffle(l)
            s = bytes(bytearray(l))
            with self.open(support.TESTFN, "wb") as f:
                f.write(s)
            with self.open(support.TESTFN, self.read_mode, buffering=0) as raw:
                bufio = self.tp(raw, 8)
                errors = []
                results = []
                def f():
                    try:
                        # Intra-buffer read then buffer-flushing read
                        for n in cycle([1, 19]):
                            s = bufio.read(n)
                            if not s:
                                break
                            # list.append() is atomic
                            results.append(s)
                    except Exception as e:
                        errors.append(e)
                        raise
                threads = [threading.Thread(target=f) for x in range(20)]
                for t in threads:
                    t.start()
                time.sleep(0.02) # yield
                for t in threads:
                    t.join()
                self.assertFalse(errors,
                    "the following exceptions were caught: %r" % errors)
                s = b''.join(results)
                for i in range(256):
                    c = bytes(bytearray([i]))
                    self.assertEqual(s.count(c), N)
        finally:
            support.unlink(support.TESTFN) 
Example 59
Project: pyblish-win   Author: pyblish   File: test_threading.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_finalize_runnning_thread(self):
        # Issue 1402: the PyGILState_Ensure / _Release functions may be called
        # very late on python exit: on deallocation of a running thread for
        # example.
        try:
            import ctypes
        except ImportError:
            self.skipTest('requires ctypes')

        rc = subprocess.call([sys.executable, "-c", """if 1:
            import ctypes, sys, time, thread

            # This lock is used as a simple event variable.
            ready = thread.allocate_lock()
            ready.acquire()

            # Module globals are cleared before __del__ is run
            # So we save the functions in class dict
            class C:
                ensure = ctypes.pythonapi.PyGILState_Ensure
                release = ctypes.pythonapi.PyGILState_Release
                def __del__(self):
                    state = self.ensure()
                    self.release(state)

            def waitingThread():
                x = C()
                ready.release()
                time.sleep(100)

            thread.start_new_thread(waitingThread, ())
            ready.acquire()  # Be sure the other thread is waiting.
            sys.exit(42)
            """])
        self.assertEqual(rc, 42) 
Example 60
Project: pyblish-win   Author: pyblish   File: test_threading.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_finalize_with_trace(self):
        # Issue1733757
        # Avoid a deadlock when sys.settrace steps into threading._shutdown
        p = subprocess.Popen([sys.executable, "-c", """if 1:
            import sys, threading

            # A deadlock-killer, to prevent the
            # testsuite to hang forever
            def killer():
                import os, time
                time.sleep(2)
                print 'program blocked; aborting'
                os._exit(2)
            t = threading.Thread(target=killer)
            t.daemon = True
            t.start()

            # This is the trace function
            def func(frame, event, arg):
                threading.current_thread()
                return func

            sys.settrace(func)
            """],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE)
        self.addCleanup(p.stdout.close)
        self.addCleanup(p.stderr.close)
        stdout, stderr = p.communicate()
        rc = p.returncode
        self.assertFalse(rc == 2, "interpreted was blocked")
        self.assertTrue(rc == 0,
                        "Unexpected error: " + repr(stderr)) 
Example 61
Project: pyblish-win   Author: pyblish   File: test_threading.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_1_join_on_shutdown(self):
        # The usual case: on exit, wait for a non-daemon thread
        script = """if 1:
            import os
            t = threading.Thread(target=joiningfunc,
                                 args=(threading.current_thread(),))
            t.start()
            time.sleep(0.1)
            print 'end of main'
            """
        self._run_and_join(script) 
Example 62
Project: NordVPN-NetworkManager-Gui   Author: vfosterm   File: nord_nm_gui.py    GNU General Public License v3.0 4 votes vote down vote up
def verify_credentials(self):
        """
        Requests a token, salt and key from Nord api
        Sends a final hash of (salt+password)+key and token to Nord api
        Verifies responses and updates GUI
        """
        if self.user_input.text() and self.password_input.text():
            self.statusbar.showMessage('Login Success', 2000)
            self.username = self.user_input.text()
            self.password = self.password_input.text()
            self.repaint()
            time.sleep(0.5)
            self.hide()
            self.main_ui()
        else:
            self.statusbar.showMessage('Username or password field cannot be empty, 2000')
        # try:
        #     resp = requests.get('https://apself.statusbar.showMessage('Login Success', 2000)
    #                         self.username = self.user_input.text()
    #                         self.password = self.password_input.text()
    #                         self.repaint()
    #                         time.sleep(0.5)
    #                         self.hide()
    #                         self.main_ui()i.nordvpn.com/token/token/' + self.user_input.text(), timeout=5)
        #
        #     if resp.status_code == requests.codes.ok:
        #         token_json = json.loads(resp.text)
        #         token = token_json['token']
        #         salt = token_json['salt']
        #         key = token_json['key']
        #
        #         password_hash = hashlib.sha512(salt.encode() + self.password_input.text().encode())
        #         final_hash = hashlib.sha512(password_hash.hexdigest().encode() + key.encode())
        #
        #         try:
        #             resp = requests.get('https://api.nordvpn.com/token/verify/' + token + '/' + final_hash.hexdigest(), timeout=5)
        #             if resp.status_code == requests.codes.ok:
        #                 self.statusbar.showMessage('Login Success', 2000)
        #                 self.username = self.user_input.text()
        #                 self.password = self.password_input.text()
        #                 self.repaint()
        #                 time.sleep(0.5)
        #                 self.hide()
        #                 self.main_ui()
        #             else:
        #                 self.statusbar.showMessage('Invalid Credentials', 2000)
        #                 self.user_input.clear()
        #                 self.password_input.clear()
        #                 self.user_input.setFocus()
        #         except Exception as ex:
        #             self.statusbar.showMessage('Invalid Credentials', 2000)
        #             self.user_input.clear()
        #             self.password_input.clear()
        #             self.user_input.setFocus()
        #     else:
        #         self.statusbar.showMessage("API Error: could not fetch token", 2000)
        # except Exception as ex:
        #     self.statusbar.showMessage("API Error: could not fetch token", 2000)
        #     self.get_api_data() 
Example 63
Project: NordVPN-NetworkManager-Gui   Author: vfosterm   File: nord_nm_gui.py    GNU General Public License v3.0 4 votes vote down vote up
def set_kill_switch(self):
        """
        Generates bash killswitch script and moves it to the NetworkManager
        """
        script = (
            '#!/bin/bash\n'
            'PERSISTENCE_FILE=' + os.path.join(self.scripts_path, '.killswitch_data') + '\n\n'
            'case $2 in'
            '  vpn-up)\n'
            '    nmcli -f type,device connection | awk \'$1~/^vpn$/ && $2~/[^\-][^\-]/ { print $2; }\' > "${PERSISTENCE_FILE}"\n'
            '  ;;\n'
            '  vpn-down)\n'
            '    xargs -n 1 -a "${PERSISTENCE_FILE}" nmcli device disconnect\n'
            '  ;;\n'
            'esac\n'
        )

        try:
            with open(os.path.join(self.scripts_path, 'kill_switch'), 'w') as kill_switch:
                print(script, file=kill_switch)

            p1 = subprocess.Popen(['echo', self.sudo_password], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
            p2 = subprocess.Popen(['sudo', '-S', 'mv', self.scripts_path + '/kill_switch', self.network_manager_path + 'kill_switch'], stdin=p1.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            p1.stdout.close()
            p2.stdout.close()
            time.sleep(0.5)
            p3 = subprocess.Popen(['echo', self.sudo_password], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
            p4 = subprocess.Popen(['sudo', '-S', 'chown', 'root:root', self.network_manager_path + 'kill_switch'], stdin=p3.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            time.sleep(0.5)
            p3.stdout.close()
            p4.stdout.close()
            p5 = subprocess.Popen(['echo', self.sudo_password], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
            p6 = subprocess.Popen(['sudo', '-S', 'chmod', '744', self.network_manager_path + 'kill_switch'], stdin=p5.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            p5.stdout.close()
            p6.stdout.close()
            self.config['SETTINGS']['kill_switch'] = 'True'
            self.write_conf()

            self.statusbar.showMessage('Kill switch activated', 2000)
            self.repaint()
        except Exception as ex:
            print(ex) 
Example 64
Project: navitia_client   Author: leonardbinet   File: client.py    MIT License 4 votes vote down vote up
def _get(self, url, extra_params=None, verbose=False, first_request_time=None, retry_counter=0, ignore_fail=False):
        if verbose and not first_request_time:
            print("Import on url %s " % url)

        if not first_request_time:
            first_request_time = datetime.now()

        elapsed = datetime.now() - first_request_time
        if elapsed > timedelta(seconds=self.retry_timeout):
            raise navitia_client.exceptions.Timeout()

        if retry_counter > 0:
            # 0.5 * (1.5 ^ i) is an increased sleep time of 1.5x per iteration,
            # starting at 0.5s when retry_counter=0. The first retry will occur
            # at 1, so subtract that first.
            delay_seconds = 0.5 * 1.5 ** (retry_counter - 1)
            time.sleep(delay_seconds)

        full_url = os.path.join(self.core_url, url)

        try:
            response = requests.get(
                url=full_url, auth=(self.user, self.password), params=(extra_params or {}))
            self.requested_urls.append(response.url)

        except requests.exceptions.Timeout:
            if not ignore_fail:
                raise navitia_client.exceptions.Timeout()
            else:
                return False
        except Exception as e:
            if not ignore_fail:
                raise navitia_client.exceptions.TransportError(e)
            else:
                return False

        # Warn if not 200
        if response.status_code != 200:
            print("WARNING: response status_code is %s" % response.status_code)

        if response.status_code in _RETRIABLE_STATUSES:
            # Retry request.
            print("WARNING: retry number %d" % retry_counter)
            return self._get(url=url, extra_params=extra_params, first_request_time=first_request_time, retry_counter=retry_counter + 1, verbose=verbose, ignore_fail=ignore_fail)

        return response 
Example 65
Project: fs_image   Author: facebookincubator   File: test_unshare.py    MIT License 4 votes vote down vote up
def test_mount_namespace(self):
        try:
            sleep_pid = None
            with tempfile.TemporaryDirectory() as mnt_src, \
                    tempfile.TemporaryDirectory() as mnt_dest1, \
                    tempfile.TemporaryDirectory() as mnt_dest2:
                with open(os.path.join(mnt_src, 'cypa'), 'w') as outfile:
                    outfile.write('kvoh')

                def check_mnt_dest(mnt_dest: str):
                    cypa = os.path.join(mnt_dest, 'cypa')
                    # The outer NS cannot see the mount
                    self.assertFalse(os.path.exists(cypa))
                    # But we can read it from inside the namespace
                    self.assertEqual(b'kvoh', subprocess.check_output(
                        nsenter_as_user(unshare, 'cat', cypa),
                    ))

                with Unshare([Namespace.MOUNT]) as unshare:
                    # Without a PID namespace, this will outlive the
                    # __exit__ -- in fact, this process would leak but for
                    # our `finally`.
                    proc, sleep_pid = self._popen_sleep_forever(unshare)

                    subprocess.check_call(nsenter_as_root(
                        unshare, 'mount', mnt_src, mnt_dest1, '-o', 'bind',
                    ))
                    check_mnt_dest(mnt_dest1)

                    # Mount namespaces remain usable after the keepalive dies
                    self._kill_keepalive(unshare)

                    # We can make a second mount inside the namespace
                    subprocess.check_call(nsenter_as_root(
                        unshare, 'mount', mnt_src, mnt_dest2, '-o', 'bind',
                    ))
                    check_mnt_dest(mnt_dest2)
                    check_mnt_dest(mnt_dest1)  # The old mount is still good

                # Outside the context, nsenter cannot work. There's no way
                # to test the mounts are gone since we don't have any handle
                # by which to access them.  That's the point.
                with self.assertRaisesRegex(
                    RuntimeError, 'Must nsenter from inside an Unshare',
                ):
                    check_mnt_dest(mnt_dest1)

            time.sleep(2)  # Give some time for `sleep` to exit erroneously
            self.assertIs(None, proc.poll())  # Processes leak
        finally:
            # Ensure we don't leak the `sleep infinity` -- since it was
            # started via `sudo`, `subprocess` cannot kill it automatically.
            if sleep_pid:
                if proc.poll() is None:
                    os.kill(sleep_pid, signal.SIGTERM)
                proc.wait() 
Example 66
Project: mutatest   Author: EvanKepner   File: conftest.py    MIT License 4 votes vote down vote up
def sleep_timeout(tmp_path_factory):
    """A block of code with sleep timeout."""
    contents = dedent(
        """\
    import time
    def odd_loop(x):
        a = True
        b = False
        if a:
            time.sleep(3)
        return a

    print(odd_loop(5))
    """
    )

    test_timeout = dedent(
        """\
    from timeout import odd_loop

    def test_odd_loop():
        assert True
    """
    )

    folder = tmp_path_factory.mktemp("timeout_while")
    fn = folder / "timeout.py"
    bad_test_fn = folder / "test_timeout.py"

    for f, c in [(fn, contents), (bad_test_fn, test_timeout)]:
        with open(f, "w") as output_fn:
            output_fn.write(c)

    yield FileAndTest(fn, bad_test_fn)

    # fn.unlink()
    # bad_test_fn.unlink()


####################################################################################################
# TRANSFORMERS: COMPARE FIXTURES
#################################################################################################### 
Example 67
Project: weibo-login   Author: littlepinecone   File: login.py    GNU General Public License v3.0 4 votes vote down vote up
def getcookies(user, passwd):
    # 获取验证码
    sign = random.random()
    url = "https://captcha.weibo.com/api/pattern/get?ver=daf139fb2696a4540b298756bd06266a&source=ssologin&usrname=" + user + "&line=160&side=100&radius=30&_rnd=" + str(
        sign) + "&callback=pl_cb"
    r = requests.get(url)
    imgdata = json.loads(r.text.replace("pl_cb(", '').replace(")", ''))['path_enc']
    id = json.loads(r.text.replace("pl_cb(", '').replace(")", ''))['id']
    recombinePattern(imgdata)
    data_enc = pathdataEncode(path_generate(patterntohash()))
    path_enc = pathEncode(patterntohash(), id)

    url2 = "https://captcha.weibo.com/api/pattern/verify?ver=daf139fb2696a4540b298756bd06266a&id=" + id + "&usrname=" + user + "&source=ssologin&path_enc=" + path_enc + "&data_enc=" + data_enc + "&callback=pl_cb"
    url3 = 'https://passport.weibo.cn/sso/login'
    # 必要的等待时间
    time.sleep(1)
    # 验证验证码
    session = requests.Session()
    r2 = session.get(url2)
    # print r2.headers
    print json.loads(r2.text.replace("pl_cb(", '').replace(")", ''))['msg']
    # print id

    formdata = {'username': user,
                'password': passwd,
                'savestate': '1',
                'ec': '0',
                'entry': 'mweibo',
                'mainpageflag': '1',
                'vid': id,
                'wentry': '',
                'loginfrom': '',
                'client_id': '',
                'code:qq': '',
                'r': '',
                'pagerefer': '',
                'hff': '',
                'hfp': ''}

    # print formdata['vid']
    # 登录
    r3 = session.post(url3, data=formdata, headers=headers3)
    cookies_url = r3.headers['Set-Cookie']
    print json.loads(r3.content)['msg']
    return {k.split('=')[0]: k.split('=')[1] for k in cookies_url.split(';')}

    # r4 = requests.get('https://m.weibo.cn/')
    # print r4.headers['Set-Cookie'] 
Example 68
Project: clikit   Author: sdispater   File: test_progress_indicator.py    MIT License 4 votes vote down vote up
def test_default_indicator(ansi_io):
    bar = ProgressIndicator(ansi_io)
    bar.start("Starting...")
    time.sleep(0.101)
    bar.advance()
    time.sleep(0.101)
    bar.advance()
    time.sleep(0.101)
    bar.advance()
    time.sleep(0.101)
    bar.advance()
    time.sleep(0.101)
    bar.advance()
    time.sleep(0.101)
    bar.set_message("Advancing...")
    bar.advance()
    bar.finish("Done...")
    bar.start("Starting Again...")
    time.sleep(0.101)
    bar.advance()
    bar.finish("Done Again...")
    bar.start("Starting Again...")
    time.sleep(0.101)
    bar.advance()
    bar.finish("Done Again...", reset_indicator=True)

    output = [
        " - Starting...",
        " \\ Starting...",
        " | Starting...",
        " / Starting...",
        " - Starting...",
        " \\ Starting...",
        " \\ Advancing...",
        " | Advancing...",
        " | Done...",
    ]

    expected = "\x0D\x1B[2K" + "\x0D\x1B[2K".join(output)

    expected += "\n"

    output = [" - Starting Again...", " \\ Starting Again...", " \\ Done Again..."]

    expected += "\x0D\x1B[2K" + "\x0D\x1B[2K".join(output)

    expected += "\n"

    output = [" - Starting Again...", " \\ Starting Again...", " - Done Again..."]

    expected += "\x0D\x1B[2K" + "\x0D\x1B[2K".join(output)

    expected += "\n"

    assert expected == ansi_io.fetch_error() 
Example 69
Project: clikit   Author: sdispater   File: test_progress_indicator.py    MIT License 4 votes vote down vote up
def test_explicit_format(ansi_io):
    bar = ProgressIndicator(ansi_io, ProgressIndicator.NORMAL)
    bar.start("Starting...")
    time.sleep(0.101)
    bar.advance()
    time.sleep(0.101)
    bar.advance()
    time.sleep(0.101)
    bar.advance()
    time.sleep(0.101)
    bar.advance()
    time.sleep(0.101)
    bar.advance()
    time.sleep(0.101)
    bar.set_message("Advancing...")
    bar.advance()
    bar.finish("Done...")
    bar.start("Starting Again...")
    time.sleep(0.101)
    bar.advance()
    bar.finish("Done Again...")
    bar.start("Starting Again...")
    time.sleep(0.101)
    bar.advance()
    bar.finish("Done Again...", reset_indicator=True)

    output = [
        " - Starting...",
        " \\ Starting...",
        " | Starting...",
        " / Starting...",
        " - Starting...",
        " \\ Starting...",
        " \\ Advancing...",
        " | Advancing...",
        " | Done...",
    ]

    expected = "\x0D\x1B[2K" + "\x0D\x1B[2K".join(output)

    expected += "\n"

    output = [" - Starting Again...", " \\ Starting Again...", " \\ Done Again..."]

    expected += "\x0D\x1B[2K" + "\x0D\x1B[2K".join(output)

    expected += "\n"

    output = [" - Starting Again...", " \\ Starting Again...", " - Done Again..."]

    expected += "\x0D\x1B[2K" + "\x0D\x1B[2K".join(output)

    expected += "\n"

    assert expected == ansi_io.fetch_error() 
Example 70
Project: BlueLightMeter   Author: chripell   File: nordic_uart.py    Apache License 2.0 4 votes vote down vote up
def __init__(self):
        hci_path = self.BLUEZ_PATH + '/' + args.hci_interface
        bus = dbus.SystemBus(self.BLUEZ)
        hci = bus.get_object(self.BLUEZ, hci_path)
        self.blm_ = None
        checked = []
        hci.StartDiscovery(dbus_interface='org.bluez.Adapter1')
        if args.mac_address == None:
            print 'Scanning for ', args.name
            start = time.time()
            while time.time() < start + args.timeout and not self.blm_:
                root = ET.fromstring(hci.Introspect(dbus_interface='org.freedesktop.DBus.Introspectable'))
                time.sleep(1)
                for ch in root:
                    if ch.tag == 'node':
                        dname = ch.attrib['name']
                        if dname and not dname in checked:
                            checked.append(dname)
                            path = hci_path +'/' + dname
                            dev = bus.get_object(self.BLUEZ, path)
                            devp = dbus.Interface(dev, 'org.freedesktop.DBus.Properties')
                            name = devp.Get('org.bluez.Device1', 'Name')
                            if name == args.name:
                                print('Found: %s' % dname[4:].replace('_', ':'))
                                self.path_ = path
                                self.blm_ = dev
                                self.blmp_ = devp
                                self.blmd_ = dbus.Interface(dev, 'org.bluez.Device1')
                                break
        else:
            print('Connecting to MAC %s' % args.mac_address)
            path = hci_path +'/dev_' + args.mac_address.replace(':', '_')
            self.blm_ = bus.get_object(self.BLUEZ, path)
            self.blmp_ = dbus.Interface(self.blm_, 'org.freedesktop.DBus.Properties')
            self.blmd_ = dbus.Interface(self.blm_, 'org.bluez.Device1')
            
        self.blmd_.Connect()
        self.connected_ = False
        start = time.time()
        while time.time() < start + args.timeout and not self.connected_:
            self.connected_ = self.prop_get('Connected')
        if not self.connected_:
            print('Failed to connect')
            self.blmd_.Disconnect()
        print('Connected')

        gatt_read_path = self.path_ + '/service000b/char000c'
        gatt_read = bus.get_object(self.BLUEZ, gatt_read_path)
        self.gatt_read_ = dbus.Interface(gatt_read, 'org.bluez.GattCharacteristic1')
        self.gatt_read_.StartNotify()

        gatt_write_path = self.path_ + '/service000b/char000f'
        gatt_write = bus.get_object(self.BLUEZ, gatt_write_path)
        self.gatt_write_ = dbus.Interface(gatt_write, 'org.bluez.GattCharacteristic1') 
Example 71
Project: BlueLightMeter   Author: chripell   File: blm_client.py    Apache License 2.0 4 votes vote down vote up
def __init__(self):
        hci_path = self.BLUEZ_PATH + '/' + args.hci_interface
        bus = dbus.SystemBus(self.BLUEZ)
        hci = bus.get_object(self.BLUEZ, hci_path)

        self.blm_ = None
        checked = []
        hci.StartDiscovery(dbus_interface='org.bluez.Adapter1')
        if args.mac_address == None:
            print('Scanning for BlueLightMeter')
            start = time.time()
            while time.time() < start + args.timeout and not self.blm_:
                root = ET.fromstring(hci.Introspect(dbus_interface='org.freedesktop.DBus.Introspectable'))
                time.sleep(1)
                for ch in root:
                    if ch.tag == 'node':
                        dname = ch.attrib['name']
                        if dname and not dname in checked:
                            checked.append(dname)
                            path = hci_path +'/' + dname
                            dev = bus.get_object(self.BLUEZ, path)
                            devp = dbus.Interface(dev, 'org.freedesktop.DBus.Properties')
                            name = devp.Get('org.bluez.Device1', 'Name')
                            if name == args.name:
                                print('Found: %s' % dname[4:].replace('_', ':'))
                                self.path_ = path
                                self.blm_ = dev
                                self.blmp_ = devp
                                self.blmd_ = dbus.Interface(dev, 'org.bluez.Device1')
                                break
        else:
            print('Connecting to BlueLightMeter with MAC %s' % args.mac_address)
            path = hci_path +'/dev_' + args.mac_address.replace(':', '_')
            self.blm_ = bus.get_object(self.BLUEZ, path)
            self.blmp_ = dbus.Interface(self.blm_, 'org.freedesktop.DBus.Properties')
            self.blmd_ = dbus.Interface(self.blm_, 'org.bluez.Device1')

        self.blmd_.Connect()
        self.connected_ = False
        start = time.time()
        while time.time() < start + args.timeout and not self.connected_:
            self.connected_ = self.prop_get('Connected')
        if not self.connected_:
            print('Failed to connect')
            self.blmd_.Disconnect()
        print('Connected')
        time.sleep(3)

        gatt_read_path = self.path_ + '/service000c/char000d'
        gatt_read = bus.get_object(self.BLUEZ, gatt_read_path)
        self.gatt_read_ = dbus.Interface(gatt_read, 'org.bluez.GattCharacteristic1')

        gatt_write_path = self.path_ + '/service000c/char0010'
        gatt_write = bus.get_object(self.BLUEZ, gatt_write_path)
        self.gatt_write_ = dbus.Interface(gatt_write, 'org.bluez.GattCharacteristic1') 
Example 72
Project: cat-bbs   Author: aleju   File: train.py    MIT License 4 votes vote down vote up
def update_window(win, inputs, outputs_gt, model):
    """Show true and generated outputs/heatmaps for example images."""
    model.eval()

    # prepare inputs and forward through network
    inputs, outputs_gt = torch.from_numpy(inputs), torch.from_numpy(outputs_gt)
    inputs, outputs_gt = Variable(inputs), Variable(outputs_gt)
    if GPU >= 0:
        inputs = inputs.cuda(GPU)
        outputs_gt = outputs_gt.cuda(GPU)
    outputs_pred = model(inputs)

    # draw rows of resulting image
    rows = []
    for i in range(inputs.size()[0]):
        # image, ground truth outputs, predicted outputs
        img_np = (inputs[i].cpu().data.numpy() * 255).astype(np.uint8).transpose(1, 2, 0)
        hm_gt_np = outputs_gt[i].cpu().data.numpy()
        hm_pred_np = outputs_pred[i].cpu().data.numpy()

        # per image
        #   first row: ground truth outputs,
        #   second row: predicted outputs
        # each row starts with the input image, followed by heatmap images
        row_truth = [img_np] + [draw_heatmap(img_np, np.squeeze(hm_gt_np[hm_idx]), alpha=0.5) for hm_idx in range(hm_gt_np.shape[0])]
        row_pred = [img_np] + [draw_heatmap(img_np, np.squeeze(hm_pred_np[hm_idx]), alpha=0.5) for hm_idx in range(hm_pred_np.shape[0])]

        rows.append(np.hstack(row_truth))
        rows.append(np.hstack(row_pred))
    grid = np.vstack(rows)

    if SHOW_DEBUG_WINDOWS:
        # show grid in opencv window
        if cv2.getWindowProperty(win, 0) == -1:
            cv2.namedWindow(win, cv2.WINDOW_NORMAL)
            cv2.resizeWindow(win, 1200, 600)
            time.sleep(1)
        cv2.imshow(win, grid.astype(np.uint8)[:, :, ::-1])
        cv2.waitKey(10)
    else:
        # save grid to file
        misc.imsave("window_%s.jpg" % (win,), grid.astype(np.uint8)) 
Example 73
Project: alfred-yubikey-otp   Author: robertoriv   File: util.py    MIT License 4 votes vote down vote up
def acquire(self, blocking=True):
        """Acquire the lock if possible.

        If the lock is in use and ``blocking`` is ``False``, return
        ``False``.

        Otherwise, check every :attr:`delay` seconds until it acquires
        lock or exceeds attr:`timeout` and raises an :class:`AcquisitionError`.

        """
        if self.locked and not blocking:
            return False

        start = time.time()
        while True:

            # Raise error if we've been waiting too long to acquire the lock
            if self.timeout and (time.time() - start) >= self.timeout:
                    raise AcquisitionError('lock acquisition timed out')

            # If already locked, wait then try again
            if self.locked:
                time.sleep(self.delay)
                continue

            # Create in append mode so we don't lose any contents
            if self._lockfile is None:
                self._lockfile = open(self.lockfile, 'a')

            # Try to acquire the lock
            try:
                fcntl.lockf(self._lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
                self._lock.set()
                break
            except IOError as err:  # pragma: no cover
                if err.errno not in (errno.EACCES, errno.EAGAIN):
                    raise

                # Don't try again
                if not blocking:  # pragma: no cover
                    return False

                # Wait, then try again
                time.sleep(self.delay)

        return True 
Example 74
Project: dcos-proxy   Author: dparrish   File: build-config.py    Apache License 2.0 4 votes vote down vote up
def main(argv):
    try:
        old_config = None
        while True:
            params = {
                'vhosts': {},
            }

            s = requests.Session()
            apps = json.loads(s.get('http://master.mesos:8080/v2/apps').text)
            for app in apps['apps']:
                try:
                    vhost = app['labels']['VIRTUAL_HOST']
                except KeyError:
                    continue
                tasks = json.loads(s.get('http://master.mesos:8080/v2/apps%s/tasks' % app['id'],
                                         headers={'Accept': 'application/json'}).text)
                backends = []
                for task in tasks['tasks']:
                    try:
                        ip = socket.gethostbyname(task['host'])
                    except socket.gaierror:
                        print "Can't look up host %s" % task['host']
                        continue
                    backends.append('%s:%s' % (ip, task['ports'][0]))
                if backends:
                    params['vhosts'][vhost] = {
                        'backends': backends,
                    }

            template = Template(TEMPLATE)
            new_config = template.render(params)
            if new_config != old_config:
                with file('/etc/nginx/sites-available/default', 'w') as fh:
                    fh.write(new_config)
                test = subprocess.Popen(['/usr/sbin/nginx', '-t'], stderr=subprocess.PIPE)
                output = test.communicate()
                if test.returncode != 0:
                    if old_config:
                        print 'Error generating new NGINX configuration, not reloading'
                        return
                    else:
                        raise RuntimeError('Error generating NGINX configuration')
                subprocess.call(['/usr/sbin/nginx', '-s', 'reload'])
                old_config = new_config
            time.sleep(10)
    except KeyboardInterrupt:
        return 1 
Example 75
Project: pepper-robot-programming   Author: maverickjoy   File: asthama_search.py    MIT License 4 votes vote down vote up
def _turnTheta(self, theta, toward, withCapture):
        global PENDING_PHI

        theta = self._transformTheta(theta)

        if PENDING_PHI != 0:
            theta += PENDING_PHI
            PENDING_PHI = 0

        theta = self._transformTheta(theta)

        X = 0.0
        Y = 0.0
        Theta = theta

        y = 0
        x = False
        if float(theta) == 0.0 :
            self._printLogs("No need to turn : " + str(theta), "OKBLUE")
            x = True

        self._printLogs("Trying turning : " + str(toward), "OKBLUE")


        # while not x :
        #     if y > 1:
        #         print "Cant turn closing program"
        #         # need human intervention
        #         raw_input("Please align me in direction : "+ str(toward))
        #         break
        #
        #     print "Trying turning : ", toward
        #     x = motion_service.moveTo(X, Y, Theta)
        #     print "Turning Possible : ",x
        #     if not x:
        #         print "Trying again : ", theta
        #
        #     time.sleep(MOVEMENT_WAIT)
        #     y += 1


        if not x:
            y = self.motion_service.moveTo(X, Y, Theta)
            if not y:
                self._printLogs("Cant turn", "FAIL")
                self._printLogs("", "LINE")

                # need human intervention
                raw_input("Please align me in direction : " + str(toward)) + \
                " and press enter after it"
            else:
                self._printLogs("Turning complete with theta : " + str(theta), "OKBLUE")

        if withCapture and float(theta) != 0.0 :
            self._startImageCapturingAtGraphNode()

        return 
Example 76
Project: pepper-robot-programming   Author: maverickjoy   File: robot_velocity_caliberation.py    MIT License 4 votes vote down vote up
def main(session):
    navigation_service = session.service("ALNavigation")
    motion_service = session.service("ALMotion")
    posture_service = session.service("ALRobotPosture")

    # Wake up robot
    motion_service.wakeUp()
    posture_service.goToPosture("StandInit", 0.1)
    motion_service.moveInit()

    listOfTime = []
    print "Starting Calculation : "
    noOfIterations = 3


    for i in xrange(noOfIterations * 2):
        units = 0
        units = moveForward(motion_service)

        if units == -1:
            print "OBSTACLE In between Caliberation INCOMPLETE EXITING"
            exit()

        listOfTime.append(units)
        time.sleep(2)
        res = _turnTheta(motion_service,math.pi)

        if not res :
            print "OBSTACLE In between Caliberation INCOMPLETE EXITING"
            exit()

        time.sleep(2)

    avgUnits = 0

    for unitTime in listOfTime :
        print "Unit Time : ",unitTime
        avgUnits += unitTime

    avgUnits /= (noOfIterations * 2)

    print "Caliberation Succesfull Time Units : ",avgUnits

    return 
Example 77
Project: pyblish-win   Author: pyblish   File: test_lock.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test04_lock_timeout2(self):
        self.env.set_timeout(0, db.DB_SET_LOCK_TIMEOUT)
        self.env.set_timeout(0, db.DB_SET_TXN_TIMEOUT)
        self.env.set_timeout(123456, db.DB_SET_LOCK_TIMEOUT)
        self.env.set_timeout(7890123, db.DB_SET_TXN_TIMEOUT)

        def deadlock_detection() :
            while not deadlock_detection.end :
                deadlock_detection.count = \
                    self.env.lock_detect(db.DB_LOCK_EXPIRE)
                if deadlock_detection.count :
                    while not deadlock_detection.end :
                        pass
                    break
                time.sleep(0.01)

        deadlock_detection.end=False
        deadlock_detection.count=0
        t=Thread(target=deadlock_detection)
        import sys
        if sys.version_info[0] < 3 :
            t.setDaemon(True)
        else :
            t.daemon = True
        t.start()
        self.env.set_timeout(100000, db.DB_SET_LOCK_TIMEOUT)
        anID = self.env.lock_id()
        anID2 = self.env.lock_id()
        self.assertNotEqual(anID, anID2)
        lock = self.env.lock_get(anID, "shared lock", db.DB_LOCK_WRITE)
        start_time=time.time()
        self.assertRaises(db.DBLockNotGrantedError,
                self.env.lock_get,anID2, "shared lock", db.DB_LOCK_READ)
        end_time=time.time()
        deadlock_detection.end=True
        # Floating point rounding
        self.assertTrue((end_time-start_time) >= 0.0999)
        self.env.lock_put(lock)
        t.join()

        self.env.lock_id_free(anID)
        self.env.lock_id_free(anID2)

        if db.version() >= (4,6):
            self.assertTrue(deadlock_detection.count>0) 
Example 78
Project: pyblish-win   Author: pyblish   File: asyncore.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def poll(timeout=0.0, map=None):
    if map is None:
        map = socket_map
    if map:
        r = []; w = []; e = []
        for fd, obj in map.items():
            is_r = obj.readable()
            is_w = obj.writable()
            if is_r:
                r.append(fd)
            # accepting sockets should not be writable
            if is_w and not obj.accepting:
                w.append(fd)
            if is_r or is_w:
                e.append(fd)
        if [] == r == w == e:
            time.sleep(timeout)
            return

        try:
            r, w, e = select.select(r, w, e, timeout)
        except select.error, err:
            if err.args[0] != EINTR:
                raise
            else:
                return

        for fd in r:
            obj = map.get(fd)
            if obj is None:
                continue
            read(obj)

        for fd in w:
            obj = map.get(fd)
            if obj is None:
                continue
            write(obj)

        for fd in e:
            obj = map.get(fd)
            if obj is None:
                continue
            _exception(obj) 
Example 79
Project: pyblish-win   Author: pyblish   File: test_signal.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def readpipe_interrupted(self):
        """Perform a read during which a signal will arrive.  Return True if the
        read is interrupted by the signal and raises an exception.  Return False
        if it returns normally.
        """
        # Create a pipe that can be used for the read.  Also clean it up
        # when the test is over, since nothing else will (but see below for
        # the write end).
        r, w = os.pipe()
        self.addCleanup(os.close, r)

        # Create another process which can send a signal to this one to try
        # to interrupt the read.
        ppid = os.getpid()
        pid = os.fork()

        if pid == 0:
            # Child code: sleep to give the parent enough time to enter the
            # read() call (there's a race here, but it's really tricky to
            # eliminate it); then signal the parent process.  Also, sleep
            # again to make it likely that the signal is delivered to the
            # parent process before the child exits.  If the child exits
            # first, the write end of the pipe will be closed and the test
            # is invalid.
            try:
                time.sleep(0.2)
                os.kill(ppid, self.signum)
                time.sleep(0.2)
            finally:
                # No matter what, just exit as fast as possible now.
                exit_subprocess()
        else:
            # Parent code.
            # Make sure the child is eventually reaped, else it'll be a
            # zombie for the rest of the test suite run.
            self.addCleanup(os.waitpid, pid, 0)

            # Close the write end of the pipe.  The child has a copy, so
            # it's not really closed until the child exits.  We need it to
            # close when the child exits so that in the non-interrupt case
            # the read eventually completes, otherwise we could just close
            # it *after* the test.
            os.close(w)

            # Try the read and report whether it is interrupted or not to
            # the caller.
            try:
                d = os.read(r, 1)
                return False
            except OSError, err:
                if err.errno != errno.EINTR:
                    raise
                return True 
Example 80
Project: pyblish-win   Author: pyblish   File: test_io.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test_threads(self):
        try:
            # Write out many bytes from many threads and test they were
            # all flushed.
            N = 1000
            contents = bytes(range(256)) * N
            sizes = cycle([1, 19])
            n = 0
            queue = deque()
            while n < len(contents):
                size = next(sizes)
                queue.append(contents[n:n+size])
                n += size
            del contents
            # We use a real file object because it allows us to
            # exercise situations where the GIL is released before
            # writing the buffer to the raw streams. This is in addition
            # to concurrency issues due to switching threads in the middle
            # of Python code.
            with self.open(support.TESTFN, self.write_mode, buffering=0) as raw:
                bufio = self.tp(raw, 8)
                errors = []
                def f():
                    try:
                        while True:
                            try:
                                s = queue.popleft()
                            except IndexError:
                                return
                            bufio.write(s)
                    except Exception as e:
                        errors.append(e)
                        raise
                threads = [threading.Thread(target=f) for x in range(20)]
                for t in threads:
                    t.start()
                time.sleep(0.02) # yield
                for t in threads:
                    t.join()
                self.assertFalse(errors,
                    "the following exceptions were caught: %r" % errors)
                bufio.close()
            with self.open(support.TESTFN, "rb") as f:
                s = f.read()
            for i in range(256):
                self.assertEqual(s.count(bytes([i])), N)
        finally:
            support.unlink(support.TESTFN)