當前位置: 首頁>>代碼示例>>Python>>正文


Python queue.put方法代碼示例

本文整理匯總了Python中queue.put方法的典型用法代碼示例。如果您正苦於以下問題:Python queue.put方法的具體用法?Python queue.put怎麽用?Python queue.put使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在queue的用法示例。


在下文中一共展示了queue.put方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: prefetch_generator

# 需要導入模塊: import queue [as 別名]
# 或者: from queue import put [as 別名]
def prefetch_generator(generator, to_fetch=10):
    q = queue.Queue(maxsize=to_fetch)

    def thread_worker(queue, gen):
        for val in gen:
            queue.put(val)

        # Put a poison pill.
        queue.put(None)

    t = threading.Thread(target=thread_worker, args=(q, generator))
    try:
        t.start()
        while True:
            val = q.get()
            if val is None:
                break
            else:
                yield val
    finally:
        t.join() 
開發者ID:baidu-research,項目名稱:GloballyNormalizedReader,代碼行數:23,代碼來源:ops.py

示例2: test_send_news

# 需要導入模塊: import queue [as 別名]
# 或者: from queue import put [as 別名]
def test_send_news(support):
    address = nw0.core.address()
    topic = uuid.uuid4().hex
    data = uuid.uuid4().hex
    reply_queue = queue.Queue()
    
    support.queue.put(("send_news_to", [address, topic, reply_queue]))
    while True:
        nw0.send_news_to(address, topic, None)
        try:
            in_topic, in_data = reply_queue.get_nowait()
        except queue.Empty:
            time.sleep(0.1)
        else:
            break

    nw0.send_news_to(address, topic, data)
    while in_data is None:
        in_topic, in_data = reply_queue.get()
    
    assert in_topic, in_data == (topic, data)

#
# wait_for_news_from
# 
開發者ID:tjguk,項目名稱:networkzero,代碼行數:27,代碼來源:test_messenger.py

示例3: test_wait_for_news

# 需要導入模塊: import queue [as 別名]
# 或者: from queue import put [as 別名]
def test_wait_for_news(support):
    address = nw0.core.address()
    topic = uuid.uuid4().hex
    data = uuid.uuid4().hex
    sync_queue = queue.Queue()
    
    support.queue.put(("wait_for_news_from", [address, topic, data, sync_queue]))
    in_topic, in_data = nw0.wait_for_news_from(address, topic, wait_for_s=5)
    sync_queue.put(True)
    while in_data is None:
        in_topic, in_data = nw0.wait_for_news_from(address, topic, wait_for_s=5)
    assert (topic, data) == (in_topic, in_data)

#
# send to multiple addresses
# For now, this is disallowed as the semantics aren't
# intuitive. (It does a round-robin selection which is useful
# for things like load-scheduling but not for broadcasting).
# 
開發者ID:tjguk,項目名稱:networkzero,代碼行數:21,代碼來源:test_messenger.py

示例4: test_arg_passing

# 需要導入模塊: import queue [as 別名]
# 或者: from queue import put [as 別名]
def test_arg_passing(self):
        #Make sure that parameter passing works.
        def arg_tester(queue, arg1=False, arg2=False):
            """Use to test _thread.start_new_thread() passes args properly."""
            queue.put((arg1, arg2))

        testing_queue = queue.Queue(1)
        _thread.start_new_thread(arg_tester, (testing_queue, True, True))
        result = testing_queue.get()
        self.assertTrue(result[0] and result[1],
                        "Argument passing for thread creation using tuple failed")
        _thread.start_new_thread(arg_tester, tuple(), {'queue':testing_queue,
                                                       'arg1':True, 'arg2':True})
        result = testing_queue.get()
        self.assertTrue(result[0] and result[1],
                        "Argument passing for thread creation using kwargs failed")
        _thread.start_new_thread(arg_tester, (testing_queue, True), {'arg2':True})
        result = testing_queue.get()
        self.assertTrue(result[0] and result[1],
                        "Argument passing for thread creation using both tuple"
                        " and kwargs failed") 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:23,代碼來源:test_dummy_thread.py

示例5: unpack_observed

# 需要導入模塊: import queue [as 別名]
# 或者: from queue import put [as 別名]
def unpack_observed(annotation_info, queue, obs_file):
    """ Now that transcript has been annotated, unpack values and
        create an observed entry. Send the observed entry to the queue 
        for output to obs_file."""

    obs_ID = observed_counter.increment()
    observed = (obs_ID, annotation_info.gene_ID, annotation_info.transcript_ID, 
                annotation_info.read_ID, annotation_info.dataset,
                annotation_info.start_vertex, annotation_info.end_vertex, 
                annotation_info.start_exon, annotation_info.end_exon,
                annotation_info.start_delta, annotation_info.end_delta, 
                annotation_info.read_length, annotation_info.fraction_As,
                annotation_info.custom_label, annotation_info.allelic_label,
                annotation_info.start_support, annotation_info.end_support)
    msg = (obs_file, "\t".join([str(x) for x in observed]))
    queue.put(msg)

    return 
開發者ID:mortazavilab,項目名稱:TALON,代碼行數:20,代碼來源:talon.py

示例6: grab

# 需要導入模塊: import queue [as 別名]
# 或者: from queue import put [as 別名]
def grab(cam, queue, width, height, fps):
    global running
    capture = cv2.VideoCapture(cam)
    capture.set(cv2.CAP_PROP_FRAME_WIDTH, width)
    capture.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
    capture.set(cv2.CAP_PROP_FPS, fps)

    while(running):
        frame = {}
        capture.grab()
        retval, img = capture.retrieve(0)
        frame["img"] = img
        frame["1"] = config["1"]
        frame["2"] = config["2"]

        blur = get_blur(img, 0.05)
        frame["blur"] = blur

        if queue.qsize() < 10:
            queue.put(frame)
        else:
            print(queue.qsize()) 
開發者ID:Kurokesu,項目名稱:motorized_zoom_lens,代碼行數:24,代碼來源:main_2.8-12.py

示例7: publish_sync

# 需要導入模塊: import queue [as 別名]
# 或者: from queue import put [as 別名]
def publish_sync(queue):
    """Simulates an external publisher of messages.

    Args:
        queue (queue.Queue): Queue to publish messages to.
        n (int): Number of messages to publish.
    """
    choices = string.ascii_lowercase + string.digits

    while True:
        msg_id = str(uuid.uuid4())
        host_id = "".join(random.choices(choices, k=4))
        instance_name = f"cattle-{host_id}"
        msg = PubSubMessage(message_id=msg_id, instance_name=instance_name)
        # publish an item
        queue.put(msg)
        logging.info(f"Published {msg}")
        # simulate randomness of publishing messages
        time.sleep(random.random()) 
開發者ID:econchick,項目名稱:mayhem,代碼行數:21,代碼來源:mayhem_2.py

示例8: publish_sync

# 需要導入模塊: import queue [as 別名]
# 或者: from queue import put [as 別名]
def publish_sync(queue):
    """Simulates an external publisher of messages.

    Args:
        queue (queue.Queue): Queue to publish messages to.
        n (int): Number of messages to publish.
    """
    choices = string.ascii_lowercase + string.digits
    curr_thread = threading.current_thread()
    THREADS.add(curr_thread.ident)

    while True:
        msg_id = str(uuid.uuid4())
        host_id = "".join(random.choices(choices, k=4))
        instance_name = f"cattle-{host_id}"
        msg = PubSubMessage(message_id=msg_id, instance_name=instance_name)
        # publish an item
        queue.put(msg)
        logging.info(f"Published {msg}")
        # simulate randomness of publishing messages
        time.sleep(random.random()) 
開發者ID:econchick,項目名稱:mayhem,代碼行數:23,代碼來源:mayhem_6.py

示例9: publish

# 需要導入模塊: import queue [as 別名]
# 或者: from queue import put [as 別名]
def publish(queue, n):
    """Simulates an external publisher of messages.

    Args:
        queue (queue.Queue): Queue to publish messages to.
        n (int): Number of messages to publish.
    """
    choices = string.ascii_lowercase + string.digits
    for x in range(1, n + 1):
        host_id = "".join(random.choices(choices, k=4))
        instance_name = f"cattle-{host_id}"
        msg = PubSubMessage(message_id=x, instance_name=instance_name)
        # publish an item
        queue.put(msg)
        logging.info(f"Published {x} of {n} messages")

    # indicate the publisher is done
    queue.put(None) 
開發者ID:econchick,項目名稱:mayhem,代碼行數:20,代碼來源:mayhem_1.py

示例10: _StartProcess

# 需要導入模塊: import queue [as 別名]
# 或者: from queue import put [as 別名]
def _StartProcess(self):
        print("Command: {}".format(self.arguments))
        self.process = Popen(self.arguments, stderr=STDOUT, stdout=PIPE,
                             env=os.environ, bufsize=1, close_fds=isPosix())
        self.pid = self.process.pid

        def enqueue_output(out, queue):
            for line in iter(out.readline, ""):
                queue.put(line)
            out.close()

        self.terminal_queue = Queue.Queue()
        self.terminal_producer = threading.Thread(target=enqueue_output, args=(self.process.stdout, self.terminal_queue))
        self.terminal_consumer = threading.Thread(target=self._grab_sanitizer_trace)
        self.terminal_producer.setDaemon(True)
        self.terminal_consumer.setDaemon(True)
        self.terminal_producer.start()
        self.terminal_consumer.start() 
開發者ID:MozillaSecurity,項目名稱:peach,代碼行數:20,代碼來源:process.py

示例11: on_sub_mock

# 需要導入模塊: import queue [as 別名]
# 或者: from queue import put [as 別名]
def on_sub_mock(mocker):

    mgr = multiprocess.Manager()
    q = mgr.Queue()

    def on_subscribe(self, msg, params, websocket):
        new_params = copy.deepcopy(params)
        new_params.update({'context': msg.get('context', {})})
        q.put(self)
        return new_params

    on_sub_mock = {
        'on_subscribe':
        PickableMock(side_effect=promisify(on_subscribe), name='on_subscribe')
    }

    return on_sub_mock, q 
開發者ID:hballard,項目名稱:graphql-python-subscriptions,代碼行數:19,代碼來源:test_subscription_transport.py

示例12: producer

# 需要導入模塊: import queue [as 別名]
# 或者: from queue import put [as 別名]
def producer(pool, queue, submap_ft, refmap_ft, fname, particles,
             sx, sy, s, a, apix, coefs_method, r, nr, fftthreads=1, crop=None, pfac=2):
    log = logging.getLogger('root')
    log.debug("Producing %s" % fname)
    zreader = mrc.ZSliceReader(particles[star.UCSF.IMAGE_ORIGINAL_PATH].iloc[0])
    for i, ptcl in particles.iterrows():
        log.debug("Produce %d@%s" % (ptcl[star.UCSF.IMAGE_ORIGINAL_INDEX], ptcl[star.UCSF.IMAGE_ORIGINAL_PATH]))
        # p1r = mrc.read_imgs(stack[i], idx[i] - 1, compat="relion")
        p1r = zreader.read(ptcl[star.UCSF.IMAGE_ORIGINAL_INDEX])
        log.debug("Apply")
        ri = pool.apply_async(
            subtract_outer,
            (p1r, ptcl, submap_ft, refmap_ft, sx, sy, s, a, apix, coefs_method, r, nr),
            {"fftthreads": fftthreads, "crop": crop, "pfac": pfac})
        log.debug("Put")
        queue.put((ptcl[star.UCSF.IMAGE_INDEX], ri), block=True)
        log.debug("Queue for %s is size %d" % (ptcl[star.UCSF.IMAGE_ORIGINAL_PATH], queue.qsize()))
    zreader.close()
    log.debug("Put poison pill")
    queue.put((-1, None), block=True) 
開發者ID:asarnow,項目名稱:pyem,代碼行數:22,代碼來源:projection_subtraction.py

示例13: mock_queue

# 需要導入模塊: import queue [as 別名]
# 或者: from queue import put [as 別名]
def mock_queue(monkeypatch):

    class MockQueue:
        items = []

        def get(self, timeout=None):
            try:
                return self.items.pop()
            except IndexError:
                if timeout:
                    raise queue.Empty()
                raise

        def put(self, item):
            self.items.append(item)

    mockqueue = MockQueue()

    monkeypatch.setattr('queue.Queue', lambda: mockqueue)
    return mockqueue 
開發者ID:bigchaindb,項目名稱:bigchaindb,代碼行數:22,代碼來源:test_utils.py

示例14: source_queue

# 需要導入模塊: import queue [as 別名]
# 或者: from queue import put [as 別名]
def source_queue(self, procs, queues):
        while True:
            for index, proc in enumerate(procs):
                try:
                    queue = queues[index]
                    h, w, c = self.shape[index]
                    frames_size = w * h * c
                    nv12_data = proc.stdout.read(frames_size)
                    if len(nv12_data) != frames_size:
                        # logger.error("source_queue read error index %s len %s", index, len(nv12_data))
                        continue
                    frame = np.frombuffer(nv12_data, dtype=np.uint8)
                    img = np.array(frame, dtype=np.uint8).reshape((h, w, c))
                    if DEBUG:
                        queue.put(img)
                    else:
                        queue.put_nowait(img)
                except Exception as e:
                    # logger.error("source_queue queue full index %s", index)
                    pass 
開發者ID:Kestrong,項目名稱:capture_reid,代碼行數:22,代碼來源:source_queue.py

示例15: myPublisher

# 需要導入模塊: import queue [as 別名]
# 或者: from queue import put [as 別名]
def myPublisher(queue):
  while not queue.full():
    queue.put(1)
    print("{} Appended 1 to queue: {}".format(threading.current_thread(), queue.qsize()))
    time.sleep(1) 
開發者ID:PacktPublishing,項目名稱:Learning-Concurrency-in-Python,代碼行數:7,代碼來源:fullQueue.py


注:本文中的queue.put方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。