How to create a GUID/UUID in Python

前端 未结 8 1037
情话喂你
情话喂你 2020-11-22 16:47

How do I create a GUID in Python that is platform independent? I hear there is a method using ActivePython on Windows but it\'s Windows only because it uses COM. Is there a

8条回答
  •  失恋的感觉
    2020-11-22 17:23

    2019 Answer (for Windows):

    If you want a permanent UUID that identifies a machine uniquely on Windows, you can use this trick: (Copied from my answer at https://stackoverflow.com/a/58416992/8874388).

    from typing import Optional
    import re
    import subprocess
    import uuid
    
    def get_windows_uuid() -> Optional[uuid.UUID]:
        try:
            # Ask Windows for the device's permanent UUID. Throws if command missing/fails.
            txt = subprocess.check_output("wmic csproduct get uuid").decode()
    
            # Attempt to extract the UUID from the command's result.
            match = re.search(r"\bUUID\b[\s\r\n]+([^\s\r\n]+)", txt)
            if match is not None:
                txt = match.group(1)
                if txt is not None:
                    # Remove the surrounding whitespace (newlines, space, etc)
                    # and useless dashes etc, by only keeping hex (0-9 A-F) chars.
                    txt = re.sub(r"[^0-9A-Fa-f]+", "", txt)
    
                    # Ensure we have exactly 32 characters (16 bytes).
                    if len(txt) == 32:
                        return uuid.UUID(txt)
        except:
            pass # Silence subprocess exception.
    
        return None
    
    print(get_windows_uuid())
    

    Uses Windows API to get the computer's permanent UUID, then processes the string to ensure it's a valid UUID, and lastly returns a Python object (https://docs.python.org/3/library/uuid.html) which gives you convenient ways to use the data (such as 128-bit integer, hex string, etc).

    Good luck!

    PS: The subprocess call could probably be replaced with ctypes directly calling Windows kernel/DLLs. But for my purposes this function is all I need. It does strong validation and produces correct results.

提交回复
热议问题