Daniel Dunbar | 2f8bafe | 2009-08-01 04:11:36 +0000 | [diff] [blame] | 1 | import errno, os, sys |
Daniel Dunbar | 1db467f | 2009-07-31 05:54:17 +0000 | [diff] [blame] | 2 | |
| 3 | def warning(msg): |
| 4 | print >>sys.stderr, '%s: warning: %s' % (sys.argv[0], msg) |
| 5 | |
| 6 | def detectCPUs(): |
| 7 | """ |
| 8 | Detects the number of CPUs on a system. Cribbed from pp. |
| 9 | """ |
| 10 | # Linux, Unix and MacOS: |
| 11 | if hasattr(os, "sysconf"): |
| 12 | if os.sysconf_names.has_key("SC_NPROCESSORS_ONLN"): |
| 13 | # Linux & Unix: |
| 14 | ncpus = os.sysconf("SC_NPROCESSORS_ONLN") |
| 15 | if isinstance(ncpus, int) and ncpus > 0: |
| 16 | return ncpus |
| 17 | else: # OSX: |
| 18 | return int(os.popen2("sysctl -n hw.ncpu")[1].read()) |
| 19 | # Windows: |
| 20 | if os.environ.has_key("NUMBER_OF_PROCESSORS"): |
| 21 | ncpus = int(os.environ["NUMBER_OF_PROCESSORS"]); |
| 22 | if ncpus > 0: |
| 23 | return ncpus |
| 24 | return 1 # Default |
| 25 | |
| 26 | def mkdir_p(path): |
| 27 | """mkdir_p(path) - Make the "path" directory, if it does not exist; this |
| 28 | will also make directories for any missing parent directories.""" |
| 29 | |
| 30 | if not path or os.path.exists(path): |
| 31 | return |
| 32 | |
| 33 | parent = os.path.dirname(path) |
| 34 | if parent != path: |
| 35 | mkdir_p(parent) |
| 36 | |
| 37 | try: |
| 38 | os.mkdir(path) |
| 39 | except OSError,e: |
| 40 | # Ignore EEXIST, which may occur during a race condition. |
| 41 | if e.errno != errno.EEXIST: |
| 42 | raise |
| 43 | |
| 44 | def which(command, paths = None): |
| 45 | """which(command, [paths]) - Look up the given command in the paths string (or |
| 46 | the PATH environment variable, if unspecified).""" |
| 47 | |
| 48 | if paths is None: |
| 49 | paths = os.environ.get('PATH','') |
| 50 | |
| 51 | # Check for absolute match first. |
| 52 | if os.path.exists(command): |
| 53 | return command |
| 54 | |
| 55 | # Would be nice if Python had a lib function for this. |
| 56 | if not paths: |
| 57 | paths = os.defpath |
| 58 | |
| 59 | # Get suffixes to search. |
| 60 | pathext = os.environ.get('PATHEXT', '').split(os.pathsep) |
| 61 | |
| 62 | # Search the paths... |
| 63 | for path in paths.split(os.pathsep): |
| 64 | for ext in pathext: |
| 65 | p = os.path.join(path, command + ext) |
| 66 | if os.path.exists(p): |
| 67 | return p |
| 68 | |
| 69 | return None |
| 70 | |