1 | # |
---|
2 | # executable.py -- Utilities for dealing with external executables |
---|
3 | # |
---|
4 | |
---|
5 | import os |
---|
6 | import subprocess |
---|
7 | |
---|
8 | def exists(file): |
---|
9 | """Is this an executable file?""" |
---|
10 | return os.path.isfile(file) and os.access(file, os.X_OK) |
---|
11 | |
---|
12 | def find(file, dirs=None): |
---|
13 | """Search for an executable in a given list of directories. |
---|
14 | If no directories are given, search according to the PATH |
---|
15 | environment variable.""" |
---|
16 | if not dirs: |
---|
17 | dirs = os.environ["PATH"].split(os.pathsep) |
---|
18 | for path in dirs: |
---|
19 | if is_executable(os.path.join(path, file)): |
---|
20 | return os.path.join(path, file) |
---|
21 | elif is_executable(os.path.join(path, "%s.exe" % file)): |
---|
22 | return os.path.join(path, "%s.exe" % file) |
---|
23 | return None |
---|
24 | |
---|
25 | def output(cmd, strip=None): |
---|
26 | """Run a command and collect all output""" |
---|
27 | # Check that cmd is in PATH (otherwise we'd get a generic OSError later) |
---|
28 | import distutils.spawn |
---|
29 | if type(cmd) == type(''): |
---|
30 | cmdname = cmd |
---|
31 | elif type(cmd) == type([]): |
---|
32 | cmdname = cmd[0] |
---|
33 | if distutils.spawn.find_executable(cmdname) is None: |
---|
34 | return None |
---|
35 | |
---|
36 | # Run it |
---|
37 | (output, empty_stderr) = subprocess.Popen(cmd, stdout=subprocess.PIPE, \ |
---|
38 | stderr=subprocess.STDOUT).communicate() |
---|
39 | if strip: |
---|
40 | return output.strip() |
---|
41 | else: |
---|
42 | return output |
---|
43 | |
---|
44 | def run(cmd): |
---|
45 | """Run a command""" |
---|
46 | exit_code = os.system(cmd) |
---|
47 | assert(not exit_code) |
---|