Blink Reformat | 4c46d09 | 2018-04-07 15:32:37 +0000 | [diff] [blame] | 1 | # Copyright 2016 The Chromium Authors. All rights reserved. |
| 2 | # Use of this source code is governed by a BSD-style license that can be |
| 3 | # found in the LICENSE file. |
| 4 | |
| 5 | import os |
| 6 | from os import path |
| 7 | import sys |
| 8 | |
| 9 | |
| 10 | # Based on http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python. |
| 11 | def which(program): |
| 12 | |
| 13 | def is_executable(fpath): |
| 14 | return path.isfile(fpath) and os.access(fpath, os.X_OK) |
| 15 | |
| 16 | fpath, fname = path.split(program) |
| 17 | if fpath: |
| 18 | if is_executable(program): |
| 19 | return program |
| 20 | return None |
| 21 | env_paths = os.environ["PATH"].split(os.pathsep) |
| 22 | if sys.platform == "win32": |
| 23 | env_paths = get_windows_path(env_paths) |
| 24 | for part in env_paths: |
| 25 | part = part.strip('\"') |
| 26 | file = path.join(part, program) |
| 27 | if is_executable(file): |
| 28 | return file |
| 29 | if sys.platform == "win32" and not file.endswith(".exe"): |
| 30 | file_exe = file + ".exe" |
| 31 | if is_executable(file_exe): |
| 32 | return file_exe |
| 33 | return None |
| 34 | |
| 35 | |
| 36 | # Use to find 64-bit programs (e.g. Java) when using 32-bit python in Windows |
| 37 | def get_windows_path(env_paths): |
| 38 | new_env_paths = env_paths[:] |
| 39 | for env_path in env_paths: |
| 40 | env_path = env_path.lower() |
| 41 | if "system32" in env_path: |
| 42 | new_env_paths.append(env_path.replace("system32", "sysnative")) |
| 43 | return new_env_paths |