1. import json
  2. import inspect
  3. from queue import Queue
  4. def serialize_queue(queue, dry_run=False):
  5. """Serializes a queue object for diagnostics.
  6. Args:
  7. queue: The queue object to serialize.
  8. dry_run: If True, only prints the code that would be executed.
  9. If False, actually serializes and returns the string.
  10. Returns:
  11. A string representation of the queue object, or None if dry_run is True.
  12. """
  13. if dry_run:
  14. print("Dry run mode: Printing code to be executed.")
  15. code = f"""
  16. queue_data = {{
  17. 'q': {repr(queue.queue)},
  18. 'qsize': {repr(queue.qsize)},
  19. 'is_empty': {repr(queue.empty())},
  20. 'maxsize': {repr(queue.maxsize)}
  21. }}
  22. return json.dumps(queue_data)
  23. """
  24. return None
  25. else:
  26. queue_data = {
  27. 'q': queue.queue,
  28. 'qsize': queue.qsize,
  29. 'is_empty': queue.empty(),
  30. 'maxsize': queue.maxsize
  31. }
  32. return json.dumps(queue_data, indent=4) # indent for readability
  33. if __name__ == '__main__':
  34. # Example Usage
  35. q = Queue()
  36. q.put(1)
  37. q.put(2)
  38. q.put(3)
  39. # Serialize with dry-run
  40. serialize_queue(q, dry_run=True)
  41. # Serialize without dry-run
  42. serialized_string = serialize_queue(q)
  43. print(serialized_string)

Add your comment