Search code examples
pythonintpopentraceback

Python: ValueError: invalid literal for int() with base 10: ' '


I am getting this error ValueError in my vi editor running python v2.6, i cannot update it. After a lot of research and testing I cannot figure it out. Is there anyway to assign a base value of 10 with this current code? Any suggestions for changing and restructuring? If anyone has run into similar issues and has a way they got around I'd love to know for future reference.

Here is my code:

    numcpu = sub.Popen("($(cat /proc/cpuinfo | grep 'physical id' | awk '{print $NF}' | sort | uniq | wc -l))", shell=True, stdout=sub.PIPE, stderr=sub.PIPE)
    numcores = sub.Popen("($(cat /proc/cpuinfo | grep 'cpu cores' | awk '{print $NF}' | sort | uniq | wc -l))", shell=True, stdout=sub.PIPE, stderr=sub.PIPE)
    numsibling = sub.Popen("($(cat /proc/cpuinfo | grep 'siblings' | awk '{print $NF}' | sort | uniq | wc -l))", shell=True, stdout=sub.PIPE, stderr=sub.PIPE)

    numthreads = int(numsibling.stdout.readline())/int(numcores.stdout.readline())

    if numsibling == 0 :
            maxcpuload = int(numcpu) * int(numcores)
    else:
            maxcpuload = ((int(numcpu) * int(numcores)+ int(numsibling))/2 )

My error:

Traceback (most recent call last):
  File "./cputool", line 46, in <module>
cputool()
  File "./cputool", line 31, in cputool
     numthreads = int(numsibling.stdout.readline())/int(numcores.stdout.readline())
ValueError: invalid literal for int() with base 10: ''

Solution

  • One of the strings numsibling.stdout.readline() or numcores.stdout.readline() is empty. So when you try to parse its integer value with the function int, it returns an error.

    Probably you could use a default when an empty string is passed, something like:

    int(numsibling.stdout.readline() or '0')
    

    This way even if the variable is empty, you will have 0 in place of an error.