Python - How to find UUID of computer and set as variable

Bill D picture Bill D · Sep 11, 2016 · Viewed 9.8k times · Source

I have been looking all over the internet for a way to find a way to get UUID for a computer and set it as a variable in python.

Some of the ways I tried doing didn't work.

Original idea:

import os
x = os.system("wmic diskdrive get serialnumber")
print(x)

However this does not work, and only returns 0.

I am wondering if their is a way i can find a unique Harddrive ID or any other type of identifier in python.

Answer

slashCoder picture slashCoder · Sep 11, 2016

The os.system function returns the exit code of the executed command, not the standard output of it.

According to Python official documentation:

On Unix, the return value is the exit status of the process encoded in the format specified for wait().

On Windows, the return value is that returned by the system shell after running command.

To get the output as you want, the recommended approach is to use some of the functions defined in the subprocess module. Your scenario is pretty simple, so subprocess.check_output works just fine for it.

You just need to replace the code you posted code with this instead:

import subprocess
x = subprocess.check_output('wmic csproduct get UUID')
print(x)