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()