如何将 rabbitMQ 消息保存到 csv 文件?

How to save rabbitMQ messages to csv file?

我是 rabbitMQ 的新手,我在 rabbitMQ 页面上使用了 python 的“Hello world”教程。是否有可能将消息存储到 CSV 文件中?我想存储包含子字符串测试的消息。

我有一个send.py

import pika

connection = pika.BlockingConnection(
    pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

channel.queue_declare(queue='hello')

channel.basic_publish(exchange='', routing_key='hello', body='Hello World!')
selections = ['test-1223', '1test', 'something', 'earth']
substring = 'test'
for market in selections:
    if substring in market:
        print(market)
connection.close()

和receive.py

import pika, sys, os

def main():
    connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
    channel = connection.channel()

    channel.queue_declare(queue='hello')

    def callback(ch, method, properties, body):
        print(" [x] Received %r" % body)
    channel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True)

    print(' [*] Waiting for messages. To exit press CTRL+C')
    channel.start_consuming()


if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print('Interrupted')
        try:
            sys.exit(0)
        except SystemExit:
            os._exit(0)

感谢您的帮助。

您可以使用 csv 模块处理 csv。喜欢

import csv

if "test" in body:
    with open('messages.csv', mode='a') as msg_file:
        msg_writer = csv.writer(msg_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
        msg_writer.writerow([body])