gpt4 book ai didi

python-3.x - 如何从目录循环记录并传递到python中的MQ函数?

转载 作者:行者123 更新时间:2023-12-01 04:23:05 25 4
gpt4 key购买 nike

我在一个目录中设置了 xmls XML .

123.xml
234.xml
567.xml

我希望我的代码循环到目录和每个 xml 并传递到 MQ。

目前,我能够使用当前代码成功发送 1 个 XML。

我不确定如何自动创建增量 UUID对于文件夹中的每个 XML 以及如何在下面的代码中循环。

硬编码 XML 值的当前工作代码
import ssl
!pip install pika
import pika
import uuid


def send(message):

uui = uuid.uuid4()
mydoc = open('123.xml')
xml = mydoc.read()


ssl_options = pika.SSLOptions(ssl._create_unverified_context())
credentials = pika.PlainCredentials(username='xxxxx', password='xxxx')
connection = pika.BlockingConnection(pika.ConnectionParameters(host='xxxx', port=5671, virtual_host ='abcd' ,
credentials=credentials, ssl_options=ssl_options))

channel = connection.channel()
channel.basic_publish(exchange='xxxxxx', routing_key='',properties=pika.BasicProperties(
headers={'uuid': str(uui)}), body=xml)
connection.close()

print(message + ' ' + str(uui))

return message

如何在 python 中做到这一点?

最佳答案

您想要目录中的 XML 列表吗?

只需读取目录并获取目录中的文件,然后循环通过它来执行您的操作。

import ssl
!pip install pika
import pika
import uuid
import os


def send(message):

xml_files = [file for file in os.listdir(path_to_your_directory) if os.path.isfile(os.path.join(path_to_your_directory, file)) and file.split('.')[-1] == 'xml']
uui = uui = uuid.uuid4()

for file in xml_file:
mydoc = open(file)
xml = mydoc.read()


ssl_options = pika.SSLOptions(ssl._create_unverified_context())
credentials = pika.PlainCredentials(username='xxxxx', password='xxxx')
connection = pika.BlockingConnection(pika.ConnectionParameters(host='xxxx', port=5671, virtual_host ='abcd' ,
credentials=credentials, ssl_options=ssl_options))

channel = connection.channel()
channel.basic_publish(exchange='xxxxxx', routing_key='',properties=pika.BasicProperties(
headers={'uuid': str(uui)}), body=xml)
connection.close()
next_uui_hex = hex(int(str(uui).replace('-','').upper(),16) + 1)
uui = uuid.UUID(next_uui_hex[2:11] + '-' + next_uui_hex[11:15] + '-' + next_uui_hex[15:19] + '-' + next_uui_hex[19:23] + '-' + next_uui_hex[23:])

print(message + ' ' + str(uui))

return message

关于python-3.x - 如何从目录循环记录并传递到python中的MQ函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60446662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com