GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — ppqueue/src/ppqueue/queue.py at main · fresh2dev/ppqueue

Expand file tree

/

queue.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
1081 lines (901 loc) · 33.1 KB
/

queue.py

Copy path

File metadata and controls

1081 lines (901 loc) · 33.1 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import logging
import multiprocessing as mp
import threading
import time
import traceback
from heapq import heappop, heappush
from typing import Any, Callable, Sequence
from uuid import uuid4
from tqdm.auto import tqdm
from .job import Job
from .utils import get_logger, is_windows_os
LOG = get_logger(__name__, level=logging.INFO)
class PulseTimer:
# Periodically runs a function in a background thread.
# src: https://stackoverflow.com/a/13151299
def __init__(
self,
*args: Any,
interval_ms: int,
fun: Callable[..., Any],
**kwargs: Any,
):
self._timer: threading.Timer | None = None
self._interval: int = interval_ms
self._function: Callable[..., Any] = fun
self._args: tuple[Any, ...] = args
self._kwargs: dict[str, Any] = kwargs
self._is_enabled: bool = False
self._is_running: bool = False
def _run(self) -> None:
self._is_running = False
self.start()
self._function(*self._args, **self._kwargs)
def start(self) -> None:
if not self._is_running:
self._timer = threading.Timer(self._interval / 1000, self._run)
self._timer.start()
self._is_running = True
self._is_enabled = True
def stop(self) -> None:
if self._timer is not None:
self._timer.cancel()
self._is_enabled = False
self._is_running = False
@property
def is_running(self) -> bool:
return self._is_running
@property
def is_enabled(self) -> bool:
return self._is_enabled
class Queue:
DEFAULT_GROUP: int | None = None
def __init__(
self,
max_concurrent: int = mp.cpu_count(),
*,
max_size: int = 0,
engine: str | type[mp.Process] | type[threading.Thread] = mp.Process,
name: str | None = None,
callback: Callable[[Job], Any] | None = None,
show_progress: bool = False,
drop_finished: bool = False,
stop_when_idle: bool = False,
pulse_freq_ms: int = 100,
no_start: bool = False,
):
"""A parallel processing job runner / data structure.
Args:
max_concurrent: max number of concurrently running jobs.
max_size: max size of the queue (default=0, unlimited).
engine: the engine used to run jobs.
name: an identifier for this queue.
callback: a callable that is called immediately after each job is finished.
show_progress: global setting for showing progress bars.
drop_finished: if True, the queue will not store finished jobs for retrieval.
stop_when_idle: if True, the queue will stop the pulse when all jobs are finished.
pulse_freq_ms: the interval at which jobs are transitioned between internal queues.
no_start: if True, do not start the queue pulse on instantiation.
Examples:
>>> from ppqueue import Queue
>>> from time import sleep
...
>>> with Queue() as queue:
... jobs = queue.map(sleep, [1, 2, 3, 4, 5])
...
>>> len(jobs)
5
"""
self._qid: str = name if name else str(uuid4())[:8]
self.show_progress: bool = show_progress
self._max_size: int = max_size
self._count_input: int = 0
self._count_output: int = 0
self._max_concurrent: int = max_concurrent
self._callback: Callable[..., Any] | None = callback
# https://opensource.com/article/17/4/grok-gil
self._lock: threading.Lock = threading.Lock()
if isinstance(engine, str):
if engine.lower() in ["thread", "threads", "threading"]:
engine = threading.Thread
elif engine.lower() in [
"process",
"processes",
"processing",
"multiprocessing",
]:
engine = mp.Process
else:
err: str = f"Unrecognized engine: {engine}. Choose either 'process' or 'thread'."
raise ValueError(err)
if engine is mp.Process and is_windows_os():
LOG.warning(
(
"multiprocessing performance is degraded on Windows systems. see: "
"https://docs.python.org/3/library/multiprocessing.html?highlight=process#the-spawn-and-forkserver-start-methods"
),
)
self._engine: type[mp.Process] | type[threading.Thread] = engine
self._waiting_groups: dict[int | None, list[Job]] = {self.DEFAULT_GROUP: []}
self._working_queue: dict[int | None, Job] = {}
self._finished_queue: list[Job] = []
self._drop_finished: bool = drop_finished
self._mp_manager: mp.Manager | None = None
self._output: dict[int, Job]
if self._engine is mp.Process:
self._mp_manager = mp.Manager()
self._output = self._mp_manager.dict()
else:
self._output = {}
LOG.debug("Initialized queue with %d max_concurrent.", self._max_concurrent)
self._pulse_freq_ms: int = pulse_freq_ms
self._timer: PulseTimer = PulseTimer(
interval_ms=self._pulse_freq_ms,
fun=self._pulse,
)
self._stop_when_idle: bool = stop_when_idle
if not no_start:
self.start()
LOG.debug("Initialized pulse.")
# decorator
def __call__(self, fun: Callable[..., Any], *args: Any, **kwargs: Any):
self.start()
def wrapped_f(iterable: Sequence[Any], *args: Any, **kwargs: Any) -> list[Job]:
for x in iterable:
self.enqueue(fun, args=[x, *args], kwargs=kwargs)
self.wait()
job_data = self.collect()
self.dispose()
return job_data
return wrapped_f
def __del__(self) -> None:
self.dispose()
def start(self) -> None:
"""Start the queue pulse."""
self._timer.start()
def stop(self) -> None:
"""Stop the queue pulse."""
self._timer.stop()
def dispose(self) -> None:
"""Stop running jobs, then clear the queue, then stop the queue pulse."""
LOG.debug("Disposing")
if self.is_running:
self._stop_all(wait=True)
self.stop()
LOG.debug("Removed jobs.")
self._output = None
LOG.debug("Removed output.")
self._finished_queue.clear() # [:] = []
LOG.debug("Removed finished.")
self._count_input = 0
self._count_output = 0
LOG.debug("Reset counters.")
if self._mp_manager is not None:
self._mp_manager.shutdown()
def _clear_waiting(self) -> None:
LOG.debug("Clearing waiting queue")
with self._lock:
keys = list(self._waiting_groups.keys())
for k in keys:
group_jobs = self._waiting_groups.get(k)
for _ in range(len(group_jobs)):
job = heappop(group_jobs)
job.cancelled = True
job.process_timestamp = time.time()
if not self._drop_finished:
heappush(self._finished_queue, job)
else:
self._count_output += 1
del self._waiting_groups[k]
def _stop_all(self, *, wait: bool = True) -> None:
self._clear_waiting()
keys = list(self._working_queue.keys())
for k in keys:
job = self._working_queue.get(k)
if job is not None:
job.stop()
if wait:
self.wait()
def __enter__(self) -> Queue:
return self
def __exit__(self, *args: Any) -> None:
self.dispose()
def __iter__(self) -> Queue:
return self
def __next__(self) -> Job:
job: Job | None = self.dequeue()
if job is None:
raise StopIteration
return job
def _pulse(self) -> None:
# Used internally; manages the queue system operations.
with self._lock:
try:
if self._stop_when_idle and self.is_idle():
self.stop()
else:
# stop expired jobs.
for job_id, job in self._working_queue.items():
if job.is_expired():
job.stop()
for job_id in list(self._working_queue.keys()):
job = self._working_queue[job_id]
if not job.is_running() and not job.is_processed():
job.join()
if not job.cancelled:
try:
(
stdout,
stderr,
exitcode,
timestamp,
) = self._output.pop(job.idx)
job.result = stdout
job.error = stderr
job.exitcode = exitcode
job.finish_timestamp = timestamp
except KeyError:
job.exception_txt = str(
Exception(
"{}\n\nNo data for data; it may have exited"
" unexpectedly.".format(job.idx),
),
)
if self._callback is not None:
try:
job.callback_result = self._callback(job)
except (
Exception # pylint: disable=broad-exception-caught
) as ex:
job.callback_result = str(ex)
job.process_timestamp = time.time()
LOG.debug("Completed job: %d", job.idx)
if not self._drop_finished:
heappush(self._finished_queue, job)
else:
self._count_output += 1
del self._working_queue[job_id]
if (
job.group is not None
and job.group != self.DEFAULT_GROUP
):
group_jobs: list[Job] = self._waiting_groups.get(
job.group,
)
if group_jobs is not None:
next_job = None
parent_exitcode = job.exitcode
while len(group_jobs) > 0:
next_job = heappop(group_jobs)
if (
parent_exitcode == 0
or not next_job.skip_on_group_error
):
break
else:
next_job.cancelled = True
next_job.exitcode = parent_exitcode
next_job.error = (
"skip_on_group_error = True and"
" preceding data ({}) exit code is {}".format(
job.idx,
parent_exitcode,
)
)
next_job.process_timestamp = time.time()
if not self._drop_finished:
heappush(
self._finished_queue,
next_job,
)
else:
self._count_output += 1
next_job = None
continue
if len(group_jobs) == 0:
del self._waiting_groups[job.group]
if next_job is not None:
self._working_queue[next_job.idx] = next_job
self._start_job(next_job)
while (
self._waiting_groups.get(self.DEFAULT_GROUP)
and self.max_concurrent - self._count_working() > 0
):
job = heappop(self._waiting_groups[self.DEFAULT_GROUP])
self._working_queue[job.idx] = job
self._start_job(job)
except: # pylint: disable=bare-except
self.stop()
LOG.error(traceback.format_exc())
finally:
LOG.debug(
"waiting=%d; working=%d; finished=%d.",
self._count_waiting(),
self._count_working(),
self._count_finished(),
)
def _count_waiting(self) -> int:
"""
Returns:
The number of pending jobs.
"""
return sum(len(v) for _, v in self._waiting_groups.items())
def _count_working(self) -> int:
"""
Returns:
The number of running jobs.
"""
return len(self._working_queue)
def _count_finished(self) -> int:
"""
Returns:
The number of completed jobs.
"""
return len(self._finished_queue)
def _count_remaining(self) -> int:
"""
Returns:
The number of unfinished jobs (i.e., waiting + working).
"""
return self.size(waiting=True, working=True)
def _sizes(
self,
*,
waiting: bool = False,
working: bool = False,
finished: bool = False,
) -> list[int]:
"""Returns the number of jobs in the corresponding queue(s).
Args:
waiting: include jobs in the waiting queue?
- Accepts: bool
- Default: False
working: include jobs in the working table?
- Accepts: bool
- Default: False
finished: include jobs in the completed queue?
- Accepts: bool
- Default: False
Note: when all are False, all jobs are counted (default).
Returns:
int
"""
counts = {}
is_locked = False
try:
to_tally = sum([waiting, working, finished])
if to_tally != 1:
if to_tally == 0:
waiting, working, finished = True, True, True
# must lock when more than 1 component included.
is_locked = self._lock.acquire()
if waiting:
counts["waiting"] = self._count_waiting()
if working:
counts["working"] = self._count_working()
if finished:
counts["finished"] = self._count_finished()
finally:
if is_locked:
self._lock.release()
return list(counts.values())
def __len__(self) -> int:
return self.size()
def size(
self,
*,
waiting: bool = False,
working: bool = False,
finished: bool = False,
) -> int:
"""Get the number of jobs in the queue in state: waiting, working, and/or finished.
If no options are given, the total number of jobs in the queue is returned.
Args:
waiting: include waiting jobs.
working: include working jobs.
finished: include finished jobs.
Returns:
...
Examples:
>>> from ppqueue import Queue
...
>>> def add_nums(x: int, y: int) -> int:
... return x + y
...
>>> with Queue() as queue:
... for i in range(5):
... _ = queue.enqueue(add_nums, args=[i, 100])
... print(queue.size())
1
2
3
4
5
"""
return sum(self._sizes(waiting=waiting, working=working, finished=finished))
def is_idle(self) -> bool:
return self._count_waiting() == 0 and self._count_working() == 0
def is_busy(self) -> bool:
"""True if max concurrent limit is reached or if there are waiting jobs.
Returns:
...
"""
return self._count_waiting() > 0 or self.max_concurrent <= self._count_working()
def is_empty(self) -> bool:
"""True if there are no jobs in the queue system.
Returns:
...
"""
return self.size() == 0
def is_full(self) -> bool:
"""True if the number of jobs in the queue system is equal to max_size.
Returns:
...
"""
return 0 < self._max_size <= self.size()
def join(self, *args, **kwargs) -> int:
return self.wait(*args, **kwargs)
def wait(
self,
*,
n: int = 0,
timeout: float = 0,
poll_ms: int = 0,
show_progress: bool | None = None,
) -> int:
"""Wait for jobs to finish.
Args:
n: the number of jobs to wait for (default=0, all).
timeout: seconds to wait before raising `TimeoutError` (default=0, indefinitely).
poll_ms: milliseconds to pause between checks (default=100).
show_progress: if True, present a progress bar.
Returns:
If `n <= 0`, returns the count of unfinished jobs.
Else, returns the count of finished jobs.
"""
if poll_ms is None or poll_ms <= 0:
poll_ms = self._pulse_freq_ms
elif poll_ms < self._pulse_freq_ms:
err: str = "`poll_ms` must be >= `ppqueue.Queue.pulse_freq_ms`"
raise ValueError(err)
if show_progress is None:
show_progress = self.show_progress
_fun: Callable[..., Any] | None = None
_target_value: int | None = None
_comparator: Callable[..., bool] | None = None
if n <= 0:
_fun = self._count_remaining
_target_value = 0
_comparator = int.__le__
else:
_fun = self._count_finished
_target_value = n
_comparator = int.__ge__
current_value: int = _fun()
if not _comparator(current_value, _target_value):
start = time.time()
pb = None
try:
if show_progress:
pb = tqdm(total=current_value, unit="op")
while not _comparator(current_value, _target_value) and (
timeout == 0 or time.time() - start < timeout
):
time.sleep(poll_ms / 1000)
tmp_value = _fun()
if pb is None:
current_value = tmp_value
else:
diff_value = current_value - tmp_value
if diff_value > 0:
current_value = tmp_value
pb.update(diff_value)
finally:
if pb:
pb.close()
return current_value
@staticmethod
def _job_wrapper(
_job: Job,
_output: dict[int, tuple[str | None, str | None, int, float]],
/,
*args: Any,
**kwargs: Any,
) -> tuple[str | None, str | None, int, float]:
# Used internally to wrap data, capture output and any exception.
stdout: str | None = None
stderr: str | None = None
exitcode: int
timestamp: float
try:
stdout = _job.fun(*args, **kwargs)
exitcode = 0
except Exception as ex: # pylint: disable=broad-exception-caught
stderr = traceback.format_exc()
exitcode = -1
if not _job.suppress_errors:
raise ex
finally:
timestamp = time.time()
_output[_job.idx] = (stdout, stderr, exitcode, timestamp)
def _start_job(self, job: Job, /) -> None:
inner_job: mp.Process | threading.Thread = self._engine(
name=str(job.idx),
target=self._job_wrapper,
args=[job, self._output, *job.args],
kwargs=job.kwargs,
)
LOG.debug("starting job %d (name=%s)", job.idx, job.name)
inner_job.start()
job.start_timestamp = time.time()
job.inner_job = inner_job
def _submit(self, job: Job, /) -> int:
"""Submits a job into the ppqueue.Queue system.
Args:
job: ...
Raises:
OverflowError: if max_size will be exceeded after adding this job.
Returns:
The number of jobs submitted to the queue.
"""
assert not (self._engine is threading.Thread and job.timeout > 0)
if self.is_full():
raise OverflowError("Max queue size exceeded.")
job.submit_timestamp = time.time()
job.qid = self._qid
self._count_input += 1
job.idx = self._count_input
if job.name is None:
job.name = job.idx
LOG.debug("queuing job %d (name=%s)", job.idx, job.name)
group_jobs = self._waiting_groups.get(job.group)
if group_jobs is not None:
heappush(group_jobs, job)
else:
group_jobs = []
self._waiting_groups[job.group] = group_jobs
# if this is the first job in this group,
# it should be pushed to the default group.
heappush(self._waiting_groups[self.DEFAULT_GROUP], job)
return job.idx
def enqueue(
self,
fun: Callable[..., Any],
/,
args: Sequence[Any] | None = None,
kwargs: dict[str, Any] | None = None,
name: str | None = None,
priority: int = 100,
group: int | None = None,
timeout: float = 0,
suppress_errors: bool = False,
skip_on_group_error: bool = False,
) -> int:
"""Adds a job to the queue.
Args:
fun: ...
args: ...
kwargs: ...
name: ...
priority: ...
group: ...
timeout: ...
suppress_errors: ...
skip_on_group_error: ...
Returns:
...
Examples:
>>> from ppqueue import Queue
...
>>> def add_nums(x: int, y: int) -> int:
... return x + y
...
>>> with Queue() as queue:
... for i in range(5):
... _ = queue.enqueue(add_nums, args=[i, 100])
...
... jobs = queue.collect(wait=True)
...
>>> [job.result for job in jobs]
[100, 101, 102, 103, 104]
"""
job = Job(
fun=fun,
args=args,
kwargs=kwargs,
name=name,
priority=priority,
group=group,
timeout=timeout,
suppress_errors=suppress_errors,
skip_on_group_error=skip_on_group_error,
)
return self._submit(job)
def put(self, *args, **kwargs) -> int:
"""Alias for `enqueue`.
Adds a job to the queue.
Args:
*args: ...
**kwargs: ...
Returns:
...
Examples:
>>> from ppqueue import Queue
...
>>> def add_nums(x: int, y: int) -> int:
... return x + y
...
>>> with Queue() as queue:
... for i in range(5):
... _ = queue.put(add_nums, args=[i, 100])
... jobs = queue.collect(wait=True)
...
>>> [job.result for job in jobs]
[100, 101, 102, 103, 104]
"""
return self.enqueue(*args, **kwargs)
def map(
self,
fun: Callable[..., Any],
iterable: Sequence[Any],
/,
*args: Any,
timeout: float = 0,
show_progress: bool | None = None,
**kwargs: Any,
) -> list[Job]:
"""Submits many jobs to the queue -- one for each item in the iterable. Waits for all to finish, then returns the results.
Args:
fun: ...
iterable: ...
*args: ...
timeout: ...
show_progress: ...
**kwargs: ...
Returns:
...
Examples:
>>> from ppqueue import Queue
>>> from time import sleep
...
>>> with Queue() as queue:
... jobs = queue.map(sleep, [1, 2, 3, 4, 5])
...
>>> len(jobs)
5
"""
for x in iterable:
job = Job(
fun=fun,
args=[x, *args],
kwargs=dict(kwargs),
timeout=timeout,
)
self._submit(job)
return self.collect(wait=True, show_progress=show_progress)
def starmap(
self,
fun: Callable[..., Any],
iterable: Sequence[Sequence[Any]],
/,
*args: Any,
timeout: float = 0,
show_progress: bool | None = None,
**kwargs: Any,
) -> list[Job]:
"""Submits many jobs to the queue -- one for each sequence in the iterable. Waits for all to finish, then returns the results.
Args:
fun: ...
iterable: ...
*args: static arguments passed to the function.
timeout: ...
show_progress: ...
**kwargs: static keyword-arguments passed to the function.
Returns:
...
Examples:
>>> from ppqueue import Queue
...
>>> def add_nums(x: int, y: int) -> int:
... return x + y
...
>>> with Queue() as queue:
... jobs = queue.starmap(
... add_nums, [(1, 2), (3, 4)]
... )
...
>>> [job.result for job in jobs]
[3, 7]
"""
for x in iterable:
job = Job(
fun=fun,
args=[*x, *args],
kwargs=dict(kwargs),
timeout=timeout,
)
self._submit(job)
return self.collect(wait=True, show_progress=show_progress)
def starmapkw(
self,
fun: Callable[..., Any],
iterable: Sequence[dict[str, Any]],
/,
*args: Any,
timeout: float = 0,
show_progress: bool | None = None,
**kwargs: Any,
) -> list[Job]:
"""Submits many jobs to the queue -- one for each dictionary in the iterable. Waits for all to finish, then returns the results.
Args:
fun: ...
iterable: ...
*args: static arguments passed to the function.
timeout: ...
show_progress: ...
**kwargs: static keyword-arguments passed to the function.
Returns:
...
Examples:
>>> from ppqueue import Queue
>>> from time import sleep
...
>>> def add_nums(x: int, y: int) -> int:
... return x + y
...
>>> with Queue() as queue:
... jobs = queue.starmapkw(
... add_nums, [{'x': 1, 'y': 2}, {'x': 3, 'y': 4}]
... )
...
>>> [job.result for job in jobs]
[3, 7]
"""
for x in iterable:
job = Job(
fun=fun,
args=list(args),
kwargs={**x, **kwargs},
timeout=timeout,
)
self._submit(job)
return self.collect(wait=True, show_progress=show_progress)
def dequeue(
self,
*,
wait: bool = False,
_peek: bool = False,
**kwargs: Any,
) -> Job | None:
"""Removes and returns the finished job with the highest priority from the queue.
Args:
wait: if no jobs are finished, wait for one.
**kwargs: passed to `Queue.wait`
Returns:
...
Examples:
>>> from ppqueue import Queue
...
>>> def add_nums(x: int, y: int) -> int:
... return x + y
...
>>> with Queue() as queue:
... for i in range(5):
... _ = queue.enqueue(add_nums, args=[i, 100])
...
... jobs = [queue.dequeue(wait=True) for _ in range(queue.size())]
...
>>> [job.result for job in jobs]
[100, 101, 102, 103, 104]
"""
if self._count_finished() == 0:
if not wait:
return None
kwargs["show_progress"] = False
self.wait(n=1, **kwargs)
job: Job
if _peek:
job = self._finished_queue[0]
else:
job = heappop(self._finished_queue)
self._count_output += 1
return job
def pop(self, *args: Any, **kwargs: Any) -> Job | None:
"""Alias for `dequeue`.
Args:
*args: ...
**kwargs: ...
Returns:
...
Examples:
>>> from ppqueue import Queue
...
>>> def add_nums(x: int, y: int) -> int:
... return x + y
...
>>> with Queue() as queue:
... for i in range(5):
... _ = queue.put(add_nums, args=[i, 100])
...
... jobs = [queue.pop(wait=True) for _ in range(queue.size())]
...
>>> [job.result for job in jobs]
[100, 101, 102, 103, 104]
"""
return self.dequeue(*args, **kwargs)
def peek(self, *args: Any, **kwargs: Any) -> Job | None:
"""Returns the job with the highest priority from the queue.
Similar to `dequeue` / `pop`, but the job remains in the queue.
Args:
*args: ...
**kwargs: ...
Returns:
...
View remainder of file in raw view
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.