cpu_info.py 2.3 KB

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