Python time.sleep() Examples

The following are 30 code examples for showing how to use time.sleep(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may want to check out the right sidebar which shows the related API usage.

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

Example 1
Project: unicorn-hat-hd   Author: pimoroni   File: weather-icons.py    License: MIT License 6 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    License: 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: indras_net   Author: gcallah   File: env.py    License: GNU General Public License v3.0 6 votes vote down vote up
def n_steps(self, steps=None, random=False):
        """
        Run for n steps.
        """
        if steps is None:
            steps = int(self.user.ask("Enter number of steps: "))
        target = self.period + steps
        self.user.tell("Running for %i steps; press Ctrl-c to halt!" % steps)
        time.sleep(3)
        try:
            while self.period < target:
                step_msg = self.step(random=random)
                if step_msg is not None:
                    self.user.tell(step_msg)
                    break
        except KeyboardInterrupt:
            pass 
Example 4
Project: incubator-spot   Author: apache   File: collector.py    License: 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 5
Project: incubator-spot   Author: apache   File: collector.py    License: 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 6
Project: incubator-spot   Author: apache   File: collector.py    License: 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 7
Project: AboveTustin   Author: kevinabrandon   File: screenshot.py    License: 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 8
Project: AboveTustin   Author: kevinabrandon   File: screenshot.py    License: 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 9
Project: clikit   Author: sdispater   File: test_progress_bar.py    License: MIT License 6 votes vote down vote up
def test_min_and_max_seconds_between_redraws(ansi_bar, ansi_io):
    ansi_bar.min_seconds_between_redraws(0.5)
    ansi_bar.max_seconds_between_redraws(2 - 1)

    ansi_bar.start()
    ansi_bar.set_progress(1)
    time.sleep(1)
    ansi_bar.set_progress(2)
    time.sleep(2)
    ansi_bar.set_progress(3)

    output = [
        "    0 [>---------------------------]",
        "    2 [->--------------------------]",
        "    3 [--->------------------------]",
    ]

    expected = "\x0D" + "\x0D".join(output)

    assert expected == ansi_io.fetch_error() 
Example 10
Project: pepper-robot-programming   Author: maverickjoy   File: human_greeter.py    License: 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 11
Project: pepper-robot-programming   Author: maverickjoy   File: asthama_search.py    License: 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 12
Project: drydock   Author: airshipit   File: orchestrator.py    License: Apache License 2.0 6 votes vote down vote up
def start(self):
        """Start executing this action."""
        self.logger.debug("Starting Noop Action.")
        self.task.set_status(hd_fields.TaskStatus.Running)
        self.task.save()
        time.sleep(5)
        self.task = self.state_manager.get_task(self.task.get_id())
        if self.task.check_terminate():
            self.logger.debug("Terminating action.")
            self.task.set_status(hd_fields.TaskStatus.Terminated)
            self.task.failure()
            self.task.add_status_msg(
                msg="Action terminated.", ctx_type='NA', ctx='NA', error=False)
        else:
            self.logger.debug("Marked task as successful.")
            self.task.set_status(hd_fields.TaskStatus.Complete)
            target_nodes = self.orchestrator.get_target_nodes(self.task)
            for n in target_nodes:
                self.task.success(focus=n.name)
            self.task.add_status_msg(
                msg="Noop action.", ctx_type='NA', ctx='NA', error=False)
        self.task.save()
        self.logger.debug("Saved task state.")
        self.logger.debug("Finished Noop Action.")
        return 
Example 13
Project: drydock   Author: airshipit   File: task.py    License: Apache License 2.0 6 votes vote down vote up
def collect_subtasks(self, action=None, poll_interval=15, timeout=300):
        """Monitor subtasks waiting for completion.

        If action is specified, only watch subtasks executing this action. poll_interval
        and timeout are measured in seconds and used for controlling the monitoring behavior.

        :param action: What subtask action to monitor
        :param poll_interval: How often to load subtask status from the database
        :param timeout: How long to continue monitoring before considering subtasks as hung
        """
        timeleft = timeout
        while timeleft > 0:
            st_list = self.statemgr.get_active_subtasks(self.task_id)
            if len(st_list) == 0:
                return True
            else:
                time.sleep(poll_interval)
                timeleft = timeleft - poll_interval

        raise errors.CollectTaskTimeout(
            "Timed out collecting subtasks for task %s." % str(self.task_id)) 
Example 14
Project: drydock   Author: airshipit   File: oob.py    License: Apache License 2.0 6 votes vote down vote up
def poweroff_node(self, node):
        """Power off a node."""
        ses = self.init_session(node)
        domain = ses.lookupByName(node.name)

        if domain.isActive():
            domain.destroy()
        else:
            self.logger.debug("Node already powered off.")
            return

        try:
            i = 3
            while i > 0:
                self.logger.debug("Polling powerstate waiting for success.")
                power_state = domain.isActive()
                if not power_state:
                    return
                time.sleep(10)
                i = i - 1
            raise errors.DriverError("Power state never matched off")
        finally:
            ses.close() 
Example 15
Project: drydock   Author: airshipit   File: driver.py    License: Apache License 2.0 6 votes vote down vote up
def execute_task(self, task_id):
        task = self.state_manager.get_task(task_id)
        task_action = task.action

        if task_action in self.supported_actions:
            # Just use the Noop action
            task_action = Noop(task, self.orchestrator, self.state_manager)
            task_runner = DriverActionRunner(task_action)
            task_runner.start()

            while task_runner.is_alive():
                time.sleep(1)

            return
        else:
            raise errors.DriverError("Unsupported action %s for driver %s" %
                                     (task_action, self.driver_desc))


# Execute a single task in a separate thread 
Example 16
Project: drydock   Author: airshipit   File: actions.py    License: Apache License 2.0 6 votes vote down vote up
def invoke(self):
        """Invoke execution of this action."""
        task = self.api_client.create_task(
            design_ref=self.design_ref,
            task_action=self.action_name,
            node_filter=self.node_filter)

        if not self.block:
            return task

        task_id = task.get('task_id')

        while True:
            time.sleep(self.poll_interval)
            task = self.api_client.get_task(task_id=task_id)
            if task.get('status',
                        '') in [TaskStatus.Complete, TaskStatus.Terminated]:
                return task 
Example 17
Project: drydock   Author: airshipit   File: test_orch_generic.py    License: Apache License 2.0 6 votes vote down vote up
def test_task_complete(self, deckhand_ingester, input_files, setup,
                           blank_state, mock_get_build_data):
        input_file = input_files.join("deckhand_fullsite.yaml")
        design_ref = "file://%s" % str(input_file)

        orchestrator = orch.Orchestrator(
            state_manager=blank_state, ingester=deckhand_ingester)
        orch_task = orchestrator.create_task(
            action=hd_fields.OrchestratorAction.Noop, design_ref=design_ref)
        orch_task.set_status(hd_fields.TaskStatus.Queued)
        orch_task.save()

        orch_thread = threading.Thread(target=orchestrator.watch_for_tasks)
        orch_thread.start()

        try:
            time.sleep(10)

            orch_task = blank_state.get_task(orch_task.get_id())

            assert orch_task.get_status() == hd_fields.TaskStatus.Complete
        finally:
            orchestrator.stop_orchestrator()
            orch_thread.join(10) 
Example 18
Project: aegea   Author: kislyuk   File: ecs.py    License: Apache License 2.0 6 votes vote down vote up
def watch(args):
    logger.info("Watching task %s (%s)", args.task_id, args.cluster)
    last_status, events_received = None, 0
    log_reader = CloudwatchLogReader("/".join([args.task_name, args.task_name, os.path.basename(args.task_id)]),
                                     log_group_name=args.task_name)
    while last_status != "STOPPED":
        res = clients.ecs.describe_tasks(cluster=args.cluster, tasks=[args.task_id])
        if len(res["tasks"]) == 1:
            task_desc = res["tasks"][0]
            if task_desc["lastStatus"] != last_status:
                logger.info("Task %s %s", args.task_id, format_task_status(task_desc["lastStatus"]))
                last_status = task_desc["lastStatus"]
        try:
            for event in log_reader:
                print_event(event)
                events_received += 1
        except ClientError as e:
            expect_error_codes(e, "ResourceNotFoundException")
        if last_status is None and events_received > 0:
            break  # Logs retrieved successfully but task record is no longer in ECS
        time.sleep(1) 
Example 19
Project: aegea   Author: kislyuk   File: batch.py    License: Apache License 2.0 6 votes vote down vote up
def watch(args, print_event_fn=print_event):
    job_desc = get_job_desc(args.job_id)
    args.job_name = job_desc["jobName"]
    logger.info("Watching job %s (%s)", args.job_id, args.job_name)
    last_status, log_reader = None, None
    while last_status not in {"SUCCEEDED", "FAILED"}:
        job_desc = get_job_desc(args.job_id)
        if job_desc["status"] != last_status:
            logger.info("Job %s %s", args.job_id, format_job_status(job_desc["status"]))
            last_status = job_desc["status"]
            if job_desc["status"] in {"RUNNING", "SUCCEEDED", "FAILED"}:
                logger.info("Job %s log stream: %s", args.job_id, job_desc.get("container", {}).get("logStreamName"))
        if job_desc["status"] in {"RUNNING", "SUCCEEDED", "FAILED"}:
            if "logStreamName" in job_desc.get("container", {}):
                args.log_stream_name = job_desc["container"]["logStreamName"]
                if log_reader is None:
                    log_reader = CloudwatchLogReader(args.log_stream_name, head=args.head, tail=args.tail)
                for event in log_reader:
                    print_event_fn(event)
        if "statusReason" in job_desc:
            logger.info("Job %s: %s", args.job_id, job_desc["statusReason"])
        if job_desc.get("container", {}).get("exitCode"):
            return SystemExit(job_desc["container"]["exitCode"])
        time.sleep(1) 
Example 20
Project: aegea   Author: kislyuk   File: logs.py    License: Apache License 2.0 6 votes vote down vote up
def filter(args):
    filter_args = dict(logGroupName=args.log_group)
    if args.log_stream:
        filter_args.update(logStreamNames=[args.log_stream])
    if args.pattern:
        filter_args.update(filterPattern=args.pattern)
    if args.start_time:
        filter_args.update(startTime=int(timestamp(args.start_time) * 1000))
    if args.end_time:
        filter_args.update(endTime=int(timestamp(args.end_time) * 1000))
    num_results = 0
    while True:
        for event in paginate(clients.logs.get_paginator("filter_log_events"), **filter_args):
            if "timestamp" not in event or "message" not in event:
                continue
            print_log_event(event)
            num_results += 1
        if args.follow:
            time.sleep(1)
        else:
            return SystemExit(os.EX_OK if num_results > 0 else os.EX_DATAERR) 
Example 21
Project: aegea   Author: kislyuk   File: __init__.py    License: Apache License 2.0 6 votes vote down vote up
def wait_for_port(host, port, timeout=600, print_progress=True):
    if print_progress:
        sys.stderr.write("Waiting for {}:{}...".format(host, port))
        sys.stderr.flush()
    start_time = time.time()
    while True:
        try:
            socket.socket().connect((host, port))
            if print_progress:
                sys.stderr.write(GREEN("OK") + "\n")
            return
        except Exception:
            time.sleep(1)
            if print_progress:
                sys.stderr.write(".")
                sys.stderr.flush()
            if time.time() - start_time > timeout:
                raise 
Example 22
Project: aegea   Author: kislyuk   File: __init__.py    License: Apache License 2.0 6 votes vote down vote up
def ensure_security_group(name, vpc, tcp_ingress=frozenset()):
    try:
        security_group = resolve_security_group(name, vpc)
    except (ClientError, KeyError):
        logger.info("Creating security group %s for %s", name, vpc)
        security_group = vpc.create_security_group(GroupName=name, Description=name)
        for i in range(90):
            try:
                clients.ec2.describe_security_groups(GroupIds=[security_group.id])
            except ClientError:
                time.sleep(1)
    for rule in tcp_ingress:
        source_security_group_id = None
        if "source_security_group_name" in rule:
            source_security_group_id = resolve_security_group(rule["source_security_group_name"], vpc).id
        ensure_ingress_rule(security_group, IpProtocol="tcp", FromPort=rule["port"], ToPort=rule["port"],
                            CidrIp=rule.get("cidr"), SourceSecurityGroupId=source_security_group_id)
    return security_group 
Example 23
Project: BASS   Author: Cisco-Talos   File: cmdline.py    License: GNU General Public License v2.0 6 votes vote down vote up
def main(args, env):
    if len(args.samples) < 2:
        sys.stderr.write("Come on, give me at least two samples :(\n")
        return 1

    bass = Bass()
    job = Job()
    def received_sigterm(signal, frame):
        sys.stderr.write("Received SIGINT\n")
        bass.terminate()

    signal.signal(signal.SIGINT, received_sigterm)
    for path in args.samples:
        job.add_sample(path)
    bass.submit_job(job)
    while not job.status in (Job.STATUS_ERROR, Job.STATUS_FINISHED, Job.STATUS_CANCELED):
        time.sleep(1) 
Example 24
Project: BASS   Author: Cisco-Talos   File: server.py    License: GNU General Public License v2.0 6 votes vote down vote up
def main(args, env):
    global Session

    if args.verbose >= 1:
        app.config['DEBUG'] = True
    sys.stderr.write("connecting to DB server {:s}\n".format(args.db))
    connection_succeeded = False
    while not connection_succeeded:
        try:
            engine = create_engine(args.db)
            Session = sessionmaker(bind = engine)
            Base.metadata.create_all(engine)
            sys.stderr.write("connection succeeded!\n")
            connection_succeeded = True
            app.run(debug = args.verbose >= 1, host = "0.0.0.0", port = 80)
        except OperationalError as err:
            if "Connection refused" in str(err):
                connection_succeeded = False
                time.sleep(10)
            else:
                raise 
Example 25
Project: RF-Monitor   Author: EarToEarOak   File: cli.py    License: GNU General Public License v2.0 6 votes vote down vote up
def __on_event(self):
        event = self._queue.get()
        if event.type == Events.SCAN_ERROR:
            self.__on_scan_error(event.data)
        elif event.type == Events.SCAN_DATA:
            self.__on_scan_data(event.data)
        elif event.type == Events.SERVER_ERROR:
            self.__on_server_error(event.data)
        elif event.type == Events.GPS_ERROR:
            self.__std_err(event.data['msg'])
            self.__restart_gps()
        elif event.type == Events.GPS_WARN:
            self.__std_err(event.data['msg'])
        elif event.type == Events.GPS_TIMEOUT:
            self.__std_err(event.data['msg'])
            self.__restart_gps()
        elif event.type == Events.GPS_LOC:
            self._location = event.data['loc']
        elif event.type == Events.PUSH_ERROR:
            if not self._warnedPush:
                self._warnedPush = True
                self.__std_err('Push failed:\n\t' + event.data['msg'])
        else:
            time.sleep(0.01) 
Example 26
Project: RF-Monitor   Author: EarToEarOak   File: gps.py    License: GNU General Public License v2.0 6 votes vote down vote up
def __serial_read(self):
        isSentence = False
        sentence = ''
        while not self._cancel:
            data = self._comm.read(1)
            if data:
                self._timeout.reset()
                if data == '$':
                    isSentence = True
                    continue
                if data == '\r' or data == '\n':
                    isSentence = False
                    if sentence:
                        yield sentence
                        sentence = ''
                if isSentence:
                    sentence += data
            else:
                time.sleep(0.1) 
Example 27
Project: pkmeter   Author: pkkid   File: pkcharts.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def attribute_values(self, values):
        if not values: return None
        values = [float(v) for v in values.split(',')]
        self.showit = False
        if len(values) == 2:
            self.showit = True
        numpoints = int(self.width() / self.pxperpt)
        if not self.data or numpoints != self.numpoints:
            self._init_data(values, numpoints)
        self.data = self.data[1:] + [values]
        if self.autoscale:
            self.maxvalue = max([max(x) for x in self.data] + [self.minmax])
            self.setToolTip('Max: %s' % self.maxvalue)
        if self.interval:
            loops = self.interval * 10
            for i in range(loops):
                self.offset = self.pxperpt * (i / float(loops))
                self.update()
                time.sleep(self.interval / float(loops))
        else:
            self.update() 
Example 28
Project: unicorn-hat-hd   Author: pimoroni   File: show_my_ip.py    License: 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 29
Project: svviz   Author: svviz   File: multiprocessor.py    License: MIT License 5 votes vote down vote up
def methodASDSDG(self, arg):
            print(arg)
            time.sleep(5) 
Example 30
Project: 21tb_robot   Author: iloghyr   File: study_robot.py    License: 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)