15
15
limitations under the License.
16
16
"""
17
17
import sys
18
+ import inspect
19
+ import os
18
20
from os import listdir , remove , makedirs
19
21
from shutil import copyfile
20
22
from os .path import isdir , join , exists , split , relpath , splitext
@@ -31,21 +33,48 @@ def cmd(l, check=True, verbose=False, shell=False, cwd=None):
31
33
32
34
33
35
def run_cmd (command , wd = None , redirect = False ):
34
- if not exists (command [0 ]):
35
- error ('run_cmd(): %s path does not exist' % command [0 ])
36
+ assert is_cmd_valid (command [0 ])
36
37
p = Popen (command , stdout = PIPE , stderr = STDOUT if redirect else PIPE , cwd = wd )
37
38
_stdout , _stderr = p .communicate ()
38
39
return _stdout , _stderr , p .returncode
39
40
40
41
41
42
def run_cmd_ext (command ):
42
- if not exists (command [0 ]):
43
- error ('run_cmd_ext(): %s path does not exist' % command [0 ])
43
+ assert is_cmd_valid (command [0 ])
44
44
p = Popen (command , stdout = PIPE , stderr = PIPE )
45
45
_stdout , _stderr = p .communicate ()
46
46
return _stdout , _stderr , p .returncode
47
47
48
48
49
+ def is_cmd_valid (cmd ):
50
+ caller = get_caller_name ()
51
+ abspath = find_cmd_abspath (cmd )
52
+ if not abspath :
53
+ error ("%s: Command '%s' can't be found" % (caller , cmd ))
54
+ if not is_exec (abspath ):
55
+ error ("%s: Command '%s' resolves to file '%s' which is not executable" % (caller , cmd , abspath ))
56
+ return True
57
+
58
+
59
+ def is_exec (path ):
60
+ return os .access (path , os .X_OK )
61
+
62
+
63
+ def find_cmd_abspath (cmd ):
64
+ """ Returns the absolute path to a command.
65
+ None is returned if no absolute path was found.
66
+ """
67
+ if exists (cmd ):
68
+ return '%s/%s' % (os .getcwd (), cmd )
69
+ if not 'PATH' in os .environ :
70
+ raise Exception ("Can't find command path for current platform ('%s')" % sys .platform )
71
+ PATH = os .environ ['PATH' ]
72
+ for path in PATH .split (os .pathsep ):
73
+ abspath = '%s/%s' % (path , cmd )
74
+ if exists (abspath ):
75
+ return abspath
76
+
77
+
49
78
def mkdir (path ):
50
79
if not exists (path ):
51
80
makedirs (path )
@@ -71,6 +100,14 @@ def delete_dir_files(dir):
71
100
remove (file )
72
101
73
102
103
+ def get_caller_name (steps = 2 ):
104
+ """
105
+ When called inside a function, it returns the name
106
+ of the caller of that function.
107
+ """
108
+ return inspect .stack ()[steps ][3 ]
109
+
110
+
74
111
def error (msg ):
75
112
print msg
76
113
sys .exit (1 )
0 commit comments