-4

I wrote a program in Python-3.6.2 on Windows 10. I want get the CPU serial number.

Here is my code:

def getserial():
    # Extract serial from cpuinfo file
    cpuserial = "0000000000000000"
    try:
        f = open('/proc/cpuinfo','r')
        for line in f:
            if line[0:6]=='Serial':
                cpuserial = line[10:26]
        f.close()
    except:
        cpuserial = "ERROR000000000"
  return cpuserial

print(getserial())

When I run the program, it prints: ERROR000000000.

How do I fix it?

5
  • What OS are you using? Commented Sep 9, 2017 at 12:46
  • @jedwards,i use windows 10. Commented Sep 9, 2017 at 12:49
  • 1
    @naghi. Do you need this to only work on windows, and not linux, osx, etc? If so, you should make this clear in your question. Commented Sep 9, 2017 at 14:10
  • @ekhumoro ,yes i want it only for windows Commented Sep 9, 2017 at 14:19
  • @naghi. Try this answer. Commented Sep 9, 2017 at 15:50

1 Answer 1

2

Your code doesn't let any exception raised. So, you don't see the error: There is no '/proc/cpuinfo' file on Windows.

I have rewrite your code like that:

def getserial():
    # Extract serial from cpuinfo file
    with open('/proc/cpuinfo','r') as f:
        for line in f:
            if line[0:6] == 'Serial':
                return line[10:26]
        return "0000000000000000"

First, I have a with statement to use the file context manager: whenever an exception is raised or not, your file will be closed.

And I simplify the loop: if it found a "Serial" entry, it returns the value.

EDIT

If you have python with a version >= 2.6 you can simply use

import multiprocessing

multiprocessing.cpu_count()

http://docs.python.org/library/multiprocessing.html#multiprocessing.cpu_count

EDIT2

The best solution I found to get the "cpuinfo" is with the py-cpuinfo library.

import cpuinfo
info = cpuinfo.get_cpu_info()
print(info)

But, I think that "Serial" entry is not standard. I can't see it on classic systems.

Sign up to request clarification or add additional context in comments.

5 Comments

,how get cpuserial in windows?
@naghi: The title is ”How get cpu cpuserial in python?” (not Windows). But I understand its frustration. There are several flaws in its question.
i want use it Unique identifier as user in windows in program,what is your offer?
@naghi: You could have it's serial number with cpuinfo.get_cpu_info().
Even if my links point to the Python 3.6.2 version, I'm pretty sure they are backward compatible… So give it a try!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.