forked from CCQC/optavc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecutable.py
More file actions
209 lines (154 loc) · 6.35 KB
/
executable.py
File metadata and controls
209 lines (154 loc) · 6.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
__all__ = ['Executable', 'which', 'ProcessError']
import os
import sys
import re
import subprocess
import inspect
# import vulcan.util.tty as tty
# import vulcan
# import vulcan.error
class Executable(object):
"""Class representing a program that can be run on the command line."""
def __init__(self, name):
self.exe = name.split(' ')
self.returncode = None
if not self.exe:
raise RuntimeError("Cannot construct executable for '%s'" % name)
def add_default_arg(self, arg):
self.exe.append(arg)
@property
def command(self):
return ' '.join(self.exe)
def __call__(self, *args, **kwargs):
"""Run this executable in a subprocess.
Arguments
args
command line arguments to the executable to run.
Optional arguments
fail_on_error
Raise an exception if the subprocess returns an
error. Default is True. When not set, the return code is
available as `exe.returncode`.
ignore_errors
An optional list/tuple of error codes that can be
*ignored*. i.e., if these codes are returned, this will
not raise an exception when `fail_on_error` is `True`.
output, error
These arguments allow you to specify new stdout and stderr
values. They default to `None`, which means the
subprocess will inherit the parent's file descriptors.
You can set these to:
- python streams, e.g. open Python file objects, or os.devnull;
- filenames, which will be automatically opened for writing; or
- `str`, as in the Python string type. If you set these to `str`,
output and error will be written to pipes and returned as
a string. If both `output` and `error` are set to `str`,
then one string is returned containing output concatenated
with error.
input
Same as output, error, but `str` is not an allowed value.
Deprecated arguments
return_output[=False]
Setting this to True is the same as setting output=str.
This argument may be removed in future Vulcan versions.
"""
fail_on_error = kwargs.pop("fail_on_error", True)
ignore_errors = kwargs.pop("ignore_errors", ())
environ = os.environ.copy()
environ.update(kwargs.pop('env', {}))
# TODO: This is deprecated. Remove in a future version.
return_output = kwargs.pop("return_output", False)
# Default values of None says to keep parent's file descriptors.
if return_output:
output = str
else:
output = kwargs.pop("output", None)
error = kwargs.pop("error", None)
input = kwargs.pop("input", None)
if input is str:
raise ValueError("Cannot use `str` as input stream.")
def streamify(arg, mode):
# if isinstance(arg, basestring):
# return open(arg, mode), True
if arg is str:
return subprocess.PIPE, False
else:
return arg, False
ostream, close_ostream = streamify(output, 'w')
estream, close_estream = streamify(error, 'w')
istream, close_istream = streamify(input, 'r')
# if they just want to ignore one error code, make it a tuple.
if isinstance(ignore_errors, int):
ignore_errors = (ignore_errors,)
quoted_args = [arg for arg in args if re.search(r'^"|^\'|"$|\'$', arg)]
if quoted_args:
print(
"Quotes in command arguments can confuse scripts like configure.",
"The following arguments may cause problems when executed:",
str("\n".join([" " + arg for arg in quoted_args])),
"Quotes aren't needed because vulcan doesn't use a shell.",
"Consider removing them")
cmd = self.exe + list(args)
cmd_line = ' '.join(cmd)
# tty.debug(cmd_line)
try:
proc = subprocess.Popen(
cmd,
stdin=istream,
stderr=estream,
stdout=ostream,
env=environ)
out, err = proc.communicate()
rc = self.returncode = proc.returncode
if fail_on_error and rc != 0 and (rc not in ignore_errors):
raise RuntimeError(
"Command exited with status %d:" % proc.returncode,
cmd_line)
if output is str or error is str:
result = ''
if output is str: result += out.decode("utf-8")
if error is str: result += err.decode("utf-8")
return result
except OSError as e:
raise RuntimeError("%s: %s" % (self.exe[0], e.strerror),
"Command: " + cmd_line)
except subprocess.CalledProcessError as e:
if fail_on_error:
raise RuntimeError(
str(e), "\nExit status %d when invoking command: %s" %
(proc.returncode, cmd_line))
finally:
if close_ostream: output.close()
if close_estream: error.close()
if close_istream: input.close()
def __eq__(self, other):
return self.exe == other.exe
def __neq__(self, other):
return not (self == other)
def __hash__(self):
return hash((type(self),) + tuple(self.exe))
def __repr__(self):
return "<exe: %s>" % self.exe
def __str__(self):
return ' '.join(self.exe)
def which(name, **kwargs):
"""Finds an executable in the path like command-line which."""
path = kwargs.get('path', os.environ.get('PATH', '').split(os.pathsep))
required = kwargs.get('required', False)
if not path:
path = []
for dir in path:
exe = os.path.join(dir, name)
if os.path.isfile(exe) and os.access(exe, os.X_OK):
return Executable(exe)
if required:
print("Requires %s. Make sure it is in your path." % name)
sys.exit(1)
return None
if __name__ == "__main__":
print(which("ls"))
ls = Executable("ls")
result = ls("-l", output=str)
print(result)
# vulcan = Executable("/opt/vulcan/bin/vulcan")
# vulcan('submit','-h')