cpu_info.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. ##
  2. ## Copyright (c) 2015 Minoca Corp. All Rights Reserved.
  3. ##
  4. ## Script Name:
  5. ##
  6. ## cpu_info.py
  7. ##
  8. ## Abstract:
  9. ##
  10. ## This script determine cpu information.
  11. ##
  12. ## Author:
  13. ##
  14. ## Chris Stevens 5-May-2015
  15. ##
  16. ## Environment:
  17. ##
  18. ## Python
  19. ##
  20. import argparse
  21. import os
  22. try:
  23. import multiprocessing
  24. except ImportError:
  25. pass
  26. def main():
  27. description = "This script collects cpu information and prints it to " \
  28. "standard out."
  29. parser = argparse.ArgumentParser(description=description)
  30. parser.add_argument("-c",
  31. "--count",
  32. help="Get the number of active cores on the system.",
  33. action="store_true")
  34. arguments = parser.parse_args()
  35. if arguments.count:
  36. cpu_count = get_cpu_count()
  37. if cpu_count < 1:
  38. print("unknown")
  39. else:
  40. print(cpu_count)
  41. return 0
  42. def get_cpu_count():
  43. ##
  44. ## Try various methods to get the cpu count. Start with the multiprocessing
  45. ## library, which should be available on Python versions 2.6 and up.
  46. ##
  47. try:
  48. return multiprocessing.cpu_count()
  49. except (NameError, NotImplementedError):
  50. pass
  51. ##
  52. ## Try using sysconf, which is available in some C librarys, including
  53. ## glibc and Minoca's libc.
  54. ##
  55. try:
  56. cpu_count = os.sysconf('SC_NPROCESSORS_ONLN')
  57. if cpu_count > 0:
  58. return cpu_count
  59. except (AttributeError, ValueError):
  60. pass
  61. ##
  62. ## Try Windows environment variables.
  63. ##
  64. try:
  65. cpu_count = int(os.environ['NUMBER_OF_PROCESSORS'])
  66. if cpu_count > 0:
  67. return cpu_count
  68. except (KeyError, ValueError):
  69. pass
  70. ##
  71. ## Try using the sysctl utility for BSD systems.
  72. ##
  73. try:
  74. sysctl = os.popen('sysctl -n hw.ncpu')
  75. cpu_count = int(sysctl.read())
  76. if cpu_count > 0:
  77. return cpu_count
  78. except (OSError, ValueError):
  79. pass
  80. ##
  81. ## Give up and return -1.
  82. ##
  83. return -1
  84. if __name__ == '__main__':
  85. exit(main())