簡體   English   中英

Python - 如何在每次 FOR 迭代中更改 UUID?

[英]Python - How do I get UUID to change on each FOR iteration?

我希望這是一個簡單的解決方法,我只是瞎了眼。 我正在編寫這個腳本來處理一些數據,但我無法改變這個 UUID 值。

在腳本的開頭,我在 FOR 循環中聲明 UUID 值,以便在每次迭代時定義該值:

from uuid import uuid4 as uid
...
for entry in df.loc():
    uuid = uid()
    ...
    logs(uuid, text)
    uuid = None

但是當腳本運行時,它不是打印一個新的 UUID(這是我所期望的,因為每次迭代都定義了變量),它無限期地打印相同的 UUID。 如您所見,我嘗試在最后添加 UUID 等於 none 以嘗試捕獲此問題,但沒有成功。

這是我的日志記錄 function:

import logging, os
#import uuid

direc = os.path.dirname(__file__)

def logs(uuid: str, message: str):
    formatter = logging.Formatter('[%(asctime)s] [{}] [%(levelname)s] | %(message)s'.format(uuid))

    file_handler = logging.FileHandler(os.path.join(direc, "main.log"))
    file_handler.setLevel(logging.INFO)
    file_handler.setFormatter(formatter)
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)
    console_handler.setFormatter(formatter)

    logger = logging.getLogger()
    if not logger.handlers:
        logger.addHandler(file_handler)
        logger.addHandler(console_handler)
        logger.setLevel(logging.INFO)

    logger.info(message)

    return logger

Output:

[2021-05-05 08:24:25,288] [1cbb447f-df61-490f-990b-3c18d1b465e3] [INFO] | Name Match...
[2021-05-05 08:24:25,291] [1cbb447f-df61-490f-990b-3c18d1b465e3] [INFO] | Number Match...
[2021-05-05 08:24:26,678] [1cbb447f-df61-490f-990b-3c18d1b465e3] [INFO] | Roles Match...
[2021-05-05 08:24:28,809] [1cbb447f-df61-490f-990b-3c18d1b465e3] [INFO] | Name Match...
[2021-05-05 08:24:28,812] [1cbb447f-df61-490f-990b-3c18d1b465e3] [INFO] | Number Match...

我希望你能幫忙!

我一寫這個就回答了。 我已經使用 UUID 定義了記錄器格式化程序,因此它是這樣設置的,之后生成的所有 UUID 都不會添加到格式化程序中。 我本可以在每次調用 function 時放棄處理程序,但我決定更改它,因此我在消息中指定 UUID。

前:

formatter = logging.Formatter('[%(asctime)s] [{}] [%(levelname)s] | %(message)s'.format(uuid))

logger.info(message)

后:

formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s')

logger.info("[" + str(uuid) + "]" + " | " + message)

Output:

[2021-05-05 08:48:48,342] [INFO] [1f458c96-6074-4e64-9c09-505f1c296876] | Name Match...
[2021-05-05 08:48:48,344] [INFO] [1f458c96-6074-4e64-9c09-505f1c296876] | Number Match...
[2021-05-05 08:48:49,480] [INFO] [1f458c96-6074-4e64-9c09-505f1c296876] | Roles Match...
[2021-05-05 08:48:51,786] [INFO] [8122f7b9-72ab-4cc8-a45e-4a3c2a43bc0d] | Name Match...
[2021-05-05 08:48:51,788] [INFO] [8122f7b9-72ab-4cc8-a45e-4a3c2a43bc0d] | Number Match...
[2021-05-05 08:48:52,850] [INFO] [8122f7b9-72ab-4cc8-a45e-4a3c2a43bc0d] | Roles Match...

我知道這不是添加連接字符串的更好方法,但我現在只需要這樣做。 清理工作將在之后!

謝謝大家!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM