Python time.sleep() Examples

The following are 30 code examples of time.sleep(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module time , or try the search function .
Example #1
Source File: weather-icons.py    From unicorn-hat-hd with MIT License 7 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
Source File: server.py    From BASS with 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 #3
Source File: __init__.py    From unicorn-hat-hd with 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 #4
Source File: test_progress_bar.py    From clikit with 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 #5
Source File: pkcharts.py    From pkmeter with 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 #6
Source File: env.py    From indras_net with 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 #7
Source File: screenshot.py    From AboveTustin with 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
Source File: collector.py    From incubator-spot with 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 #9
Source File: collector.py    From incubator-spot with 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
Source File: collector.py    From incubator-spot with 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 #11
Source File: screenshot.py    From AboveTustin with 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 #12
Source File: evillib.py    From wafw00f with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def Request(self, headers=None, path=None, params={}, delay=0, timeout=7):
        try:
            time.sleep(delay)
            if not headers: 
                h = self.headers
            else: h = headers
            req = requests.get(self.target, proxies=self.proxies, headers=h, timeout=timeout,
                    allow_redirects=self.allowredir, params=params, verify=False)
            self.log.info('Request Succeeded')
            self.log.debug('Headers: %s\n' % req.headers)
            self.log.debug('Content: %s\n' % req.content)
            self.requestnumber += 1
            return req
        except requests.exceptions.RequestException as e:
            self.log.error('Something went wrong %s' % (e.__str__())) 
Example #13
Source File: gps.py    From RF-Monitor with 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 #14
Source File: cli.py    From RF-Monitor with 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 #15
Source File: driver.py    From drydock with 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
Source File: cmdline.py    From BASS with 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 #17
Source File: human_greeter.py    From pepper-robot-programming with 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 #18
Source File: asthama_search.py    From pepper-robot-programming with 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 #19
Source File: __init__.py    From aegea with 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 #20
Source File: __init__.py    From aegea with 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 #21
Source File: logs.py    From aegea with 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 #22
Source File: batch.py    From aegea with 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 #23
Source File: ecs.py    From aegea with 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 #24
Source File: orchestrator.py    From drydock with 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 #25
Source File: test_orch_generic.py    From drydock with 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 #26
Source File: task.py    From drydock with 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 #27
Source File: oob.py    From drydock with 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 #28
Source File: actions.py    From drydock with 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 #29
Source File: test_orch_generic.py    From drydock with Apache License 2.0 5 votes vote down vote up
def test_task_termination(self, input_files, deckhand_ingester, setup,
                              blank_state):
        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(2)
            orchestrator.terminate_task(orch_task)

            time.sleep(10)
            orch_task = blank_state.get_task(orch_task.get_id())
            assert orch_task.get_status() == hd_fields.TaskStatus.Terminated
        finally:
            orchestrator.stop_orchestrator()
            orch_thread.join(10) 
Example #30
Source File: twitter-export-image-fill.py    From twitter-export-image-fill with The Unlicense 5 votes vote down vote up
def download_file(url, local_filename, is_video, tweet):
  downloaded = False
  download_tries = 3
  while not downloaded:
    if (is_video and download_video(url, local_filename)) or \
       (not is_video and download_image(url, local_filename)):
      return True
    else:
      download_tries = download_tries - 1
      if download_tries == 0:
        if not args.continue_after_failure:
          print("")
          print("")
          print("Failed to download %s after 3 tries." % url)
          print("Please try again later?")
          print("(Alternatively, use --continue-after-failure option to skip past failed files.)")
          # Output debugging info if needed
          if args.verbose:
            print("Debug info: Tweet ID = %s " % tweet['id'])
          sys.exit(-2)
        else:
          failed_files.append((tweet['id'], url))
          return False
      time.sleep(3) # Wait 3 seconds before retrying
      sys.stdout.write(".")
      sys.stdout.flush()