| 1 |
# Created by Alfred Ferrer Florensa |
| 2 |
"""Contains objects for Command Line""" |
| 3 |
|
| 4 |
import os |
| 5 |
import sys |
| 6 |
import subprocess |
| 7 |
from cgelib.utils.savers_mixin import StringCreator |
| 8 |
|
| 9 |
|
| 10 |
class ApplicationError(subprocess.CalledProcessError): |
| 11 |
"""Raised when an application returns a non-zero exit status. |
| 12 |
The exit status will be stored in the returncode attribute, similarly |
| 13 |
the command line string used in the cmd attribute, and (if captured) |
| 14 |
stdout and stderr as strings. |
| 15 |
This exception is a subclass of subprocess.CalledProcessError. |
| 16 |
""" |
| 17 |
|
| 18 |
def __init__(self, returncode, cmd, stdout="", stderr=""): |
| 19 |
"""Initialize.""" |
| 20 |
self.returncode = returncode |
| 21 |
self.cmd = cmd |
| 22 |
self.stdout = stdout |
| 23 |
self.stderr = stderr |
| 24 |
|
| 25 |
def __str__(self): |
| 26 |
"""Format the error as a string.""" |
| 27 |
# get first line of any stderr message |
| 28 |
try: |
| 29 |
msg = self.stderr.lstrip().split("\n", 1)[0].rstrip() |
| 30 |
except Exception: # TODO, ValueError? AttributeError? |
| 31 |
msg = "" |
| 32 |
if msg: |
| 33 |
return """Non-zero return code %d from %r, with the error message: |
| 34 |
%s""" % ( |
| 35 |
self.returncode, |
| 36 |
self.cmd, |
| 37 |
msg, |
| 38 |
) |
| 39 |
else: |
| 40 |
return "Non-zero return code %d from %r" % ( |
| 41 |
self.returncode, self.cmd) |
| 42 |
|
| 43 |
def __repr__(self): |
| 44 |
"""Represent the error as a string.""" |
| 45 |
return "ApplicationError(%i, %s, %s, %s)" % ( |
| 46 |
self.returncode, |
| 47 |
self.cmd, |
| 48 |
self.stdout, |
| 49 |
self.stderr, |
| 50 |
) |
| 51 |
|
| 52 |
|
| 53 |
class CommandResume(dict): |
| 54 |
|
| 55 |
def __init__(self, command, stdout="", stderr="", exec_name=None, key=None): |
| 56 |
|
| 57 |
if isinstance(command, str): |
| 58 |
self["command"] = command |
| 59 |
else: |
| 60 |
raise TypeError("Command should be a string") |
| 61 |
if isinstance(stdout, str): |
| 62 |
self["stdout"] = stdout |
| 63 |
else: |
| 64 |
raise TypeError("STDOUT should be a string") |
| 65 |
if isinstance(stderr, str): |
| 66 |
self["stderr"] = stderr |
| 67 |
else: |
| 68 |
raise TypeError("STDERR should be a string") |
| 69 |
self["parameters"] = dict() |
| 70 |
if exec_name is None: |
| 71 |
self["software_name"] = "" |
| 72 |
else: |
| 73 |
self["software_name"] = exec_name |
| 74 |
self.init_parameters(program_file=exec_name) |
| 75 |
|
| 76 |
def __str__(self): |
| 77 |
str_report = """Command:\n\t%s\nReturned STDERR\n%s\n |
| 78 |
Returned STDOUT\n%s\n\n""" % (self["command"], |
| 79 |
self["stderr"], |
| 80 |
self["stdout"]) |
| 81 |
return str_report |
| 82 |
|
| 83 |
def add_parameter(self, param, value): |
| 84 |
if param is None: |
| 85 |
raise ValueError("Parameter cannot be None") |
| 86 |
else: |
| 87 |
if value is None: |
| 88 |
value = True |
| 89 |
self["parameters"][param] = value |
| 90 |
|
| 91 |
def init_parameters(self, program_file): |
| 92 |
command_split = self["command"].split(program_file) |
| 93 |
if len(command_split) == 2 or len(command_split) == 1: |
| 94 |
param_split = command_split[-1].split() |
| 95 |
param = None |
| 96 |
value = None |
| 97 |
for str_param in param_split: |
| 98 |
if str_param.startswith("-"): |
| 99 |
if param is not None: |
| 100 |
self.add_parameter(param, value) |
| 101 |
param = str_param |
| 102 |
else: |
| 103 |
value = str_param |
| 104 |
if param is not None: |
| 105 |
self.add_parameter(param, value) |
| 106 |
else: |
| 107 |
self["parameters"] = None |
| 108 |
|
| 109 |
@staticmethod |
| 110 |
def get_unique_run_key(program, run_collection, key, delimiter=";;"): |
| 111 |
""" |
| 112 |
Input: |
| 113 |
gene_key: None-unique key |
| 114 |
res_collection: Result object created by the cgelib package. |
| 115 |
minimum_key: Key prefix |
| 116 |
delimiter: String used as delimiter inside the returned key. |
| 117 |
Output: |
| 118 |
gene_key: Unique key (string) |
| 119 |
|
| 120 |
If gene_key is found in res_collection. Creates a unique key by |
| 121 |
appending a random string ton minimum_gene_key. |
| 122 |
""" |
| 123 |
if "software_executions" in run_collection: |
| 124 |
v_num = len(run_collection["software_executions"]) + 1 |
| 125 |
vrs_str = ("V{num}").format(num=v_num) |
| 126 |
if key is None: |
| 127 |
run_key = ("{program}{deli}run{vrs}" |
| 128 |
.format(program=program, deli=delimiter, |
| 129 |
vrs=vrs_str)) |
| 130 |
else: |
| 131 |
run_key = ("{program}{deli}run{vrs}{deli}{key}" |
| 132 |
.format(program=program, deli=delimiter, |
| 133 |
vrs=vrs_str, key=key)) |
| 134 |
else: |
| 135 |
run_key = ("{key}" |
| 136 |
.format(key=key)) |
| 137 |
return run_key |
| 138 |
|
| 139 |
@staticmethod |
| 140 |
def std_executable(cmdresume, json_report, key=None): |
| 141 |
cmdresume["type"] = "software_exec" |
| 142 |
run_key = CommandResume.get_unique_run_key( |
| 143 |
program=cmdresume["software_name"], |
| 144 |
run_collection=json_report, |
| 145 |
delimiter=";;", key=key) |
| 146 |
cmdresume["key"] = run_key |
| 147 |
|
| 148 |
|
| 149 |
class CommandLineBase: |
| 150 |
"""Generic interface for constructing command line strings. |
| 151 |
This class shouldn't be called directly; it should be subclassed to |
| 152 |
provide an implementation for a specific application. You can set |
| 153 |
options when creating the wrapper object using keyword arguments - or |
| 154 |
later using their corresponding properties. |
| 155 |
""" |
| 156 |
|
| 157 |
# TODO - Replace the above example since EMBOSS doesn't work properly |
| 158 |
# if installed into a folder with a space like "C:\Program Files\EMBOSS" |
| 159 |
# |
| 160 |
# Note the call example above is not a doctest as we can't handle EMBOSS |
| 161 |
# (or any other tool) being missing in the unit tests. |
| 162 |
|
| 163 |
parameters = None # will be a list defined in subclasses |
| 164 |
|
| 165 |
allowed_attr = ["parameters", "program_name", "path_exec", "language"] |
| 166 |
|
| 167 |
|
| 168 |
def __init__(self, cmd, path_exec, language="binary", **kwargs): |
| 169 |
"""Create a new instance of a command line wrapper object.""" |
| 170 |
# Init method - should be subclassed! |
| 171 |
# |
| 172 |
# The subclass methods should look like this: |
| 173 |
# |
| 174 |
# def __init__(self, cmd="muscle", **kwargs): |
| 175 |
# self.parameters = [...] |
| 176 |
# CommandLineBase.__init__(self, cmd, **kwargs) |
| 177 |
# |
| 178 |
# i.e. There should have an optional argument "cmd" to set the location |
| 179 |
# of the executable (with a sensible default which should work if the |
| 180 |
# command is on the path on Unix), and keyword arguments. It should |
| 181 |
# then define a list of parameters, all objects derived from the base |
| 182 |
# class _ArgumentBase. |
| 183 |
# |
| 184 |
# The keyword arguments should be any valid parameter name, and will |
| 185 |
# be used to set the associated parameter. |
| 186 |
self.program_name = cmd |
| 187 |
if language == "binary" or language == None: |
| 188 |
language_str = "" |
| 189 |
else: |
| 190 |
language_str = "%s " % language |
| 191 |
self.language = language_str |
| 192 |
if path_exec != "": |
| 193 |
if not os.path.isdir(path_exec): |
| 194 |
raise OSError("The path %s is not a directory. Point to the " |
| 195 |
"directory where the executable is.") |
| 196 |
path_exec = path_exec + "/" |
| 197 |
self.path_exec = path_exec |
| 198 |
try: |
| 199 |
parameters = self.parameters |
| 200 |
except AttributeError: |
| 201 |
raise AttributeError( |
| 202 |
"Subclass should have defined self.parameters" |
| 203 |
) from None |
| 204 |
# Create properties for each parameter at run time |
| 205 |
aliases = set() |
| 206 |
for p in parameters: |
| 207 |
if not p.names: |
| 208 |
if not isinstance(p, _StaticArgument): |
| 209 |
raise TypeError("Expected %r to be of type _StaticArgument" |
| 210 |
% p) |
| 211 |
continue |
| 212 |
for name in p.names: |
| 213 |
if name in aliases: |
| 214 |
raise ValueError("Parameter alias %s multiply defined" |
| 215 |
% name) |
| 216 |
aliases.add(name) |
| 217 |
name = p.names[-1] |
| 218 |
|
| 219 |
# Beware of binding-versus-assignment confusion issues |
| 220 |
def getter(name): |
| 221 |
return lambda x: x._get_parameter(name) |
| 222 |
|
| 223 |
def setter(name): |
| 224 |
return lambda x, value: x.set_parameter(name, value) |
| 225 |
|
| 226 |
def deleter(name): |
| 227 |
return lambda x: x._clear_parameter(name) |
| 228 |
|
| 229 |
doc = p.description |
| 230 |
if isinstance(p, _SwitchArgument): |
| 231 |
doc += ( |
| 232 |
"\n\nThis property controls the addition of the %s " |
| 233 |
"switch, treat this property as a boolean." % p.names[0] |
| 234 |
) |
| 235 |
else: |
| 236 |
doc += ( |
| 237 |
"\n\nThis controls the addition of the %s parameter " |
| 238 |
"and its associated value. Set this property to the " |
| 239 |
"argument value required." % p.names[0] |
| 240 |
) |
| 241 |
prop = property(getter(name), setter(name), deleter(name), doc) |
| 242 |
setattr(self.__class__, name, prop) # magic! |
| 243 |
for key, value in kwargs.items(): |
| 244 |
self.set_parameter(key, value) |
| 245 |
|
| 246 |
def _validate(self): |
| 247 |
"""Make sure the required parameters have been set (PRIVATE). |
| 248 |
Check that incompatible paramters are not set. |
| 249 |
No return value - it either works or raises a ValueError. |
| 250 |
This is a separate method (called from __str__) so that subclasses may |
| 251 |
override it. |
| 252 |
""" |
| 253 |
param_set = [] |
| 254 |
for p in self.parameters: |
| 255 |
if(p.is_set): |
| 256 |
param_set.append(p.names[-1]) |
| 257 |
# Check for missing required parameters: |
| 258 |
if p.is_required is True and not (p.is_set): |
| 259 |
if not (p.alter_options): |
| 260 |
raise ValueError("Required parameter %s is not set." |
| 261 |
% p.names[-1]) |
| 262 |
required_exists = 0 |
| 263 |
for p_set in self.parameters: |
| 264 |
if p_set.is_set and p_set.names[-1] in p.alter_options: |
| 265 |
required_exists = 1 |
| 266 |
continue |
| 267 |
if not required_exists: |
| 268 |
raise ValueError("Parameter %s is not set. Neither " |
| 269 |
"alternative parameters as %s." |
| 270 |
% (p.names[-1], |
| 271 |
', '.join(p.alter_options))) |
| 272 |
# Check for incompatible paramters set |
| 273 |
if p.incompatible is not None and p.is_set: |
| 274 |
arg_incompatible = set(p.incompatible) & set(param_set) |
| 275 |
if arg_incompatible: |
| 276 |
raise ValueError("Parameter '%s' is set, but the " |
| 277 |
"incompatible parameter '%s' has " |
| 278 |
"been also set." |
| 279 |
% (p.names[-1], |
| 280 |
', '.join(arg_incompatible))) |
| 281 |
|
| 282 |
def __str__(self): |
| 283 |
"""Make the commandline string with the currently set options. |
| 284 |
e.g. |
| 285 |
>>> from Bio.Emboss.Applications import WaterCommandline |
| 286 |
>>> cline = WaterCommandline(gapopen=10, gapextend=0.5) |
| 287 |
>>> cline.asequence = "asis:ACCCGGGCGCGGT" |
| 288 |
>>> cline.bsequence = "asis:ACCCGAGCGCGGT" |
| 289 |
>>> cline.outfile = "temp_water.txt" |
| 290 |
>>> print(cline) |
| 291 |
water -outfile=temp_water.txt -asequence=asis:ACCCGGGCGCGGT |
| 292 |
-bsequence=asis:ACCCGAGCGCGGT -gapopen=10 -gapextend=0.5 |
| 293 |
>>> str(cline) |
| 294 |
'water -outfile=temp_water.txt -asequence=asis:ACCCGGGCGCGGT |
| 295 |
-bsequence=asis:ACCCGAGCGCGGT -gapopen=10 -gapextend=0.5' |
| 296 |
""" |
| 297 |
self._validate() |
| 298 |
commandline = "%s%s%s " % (_escape_filename(self.language), |
| 299 |
_escape_filename(self.path_exec), |
| 300 |
_escape_filename(self.program_name)) |
| 301 |
for parameter in self.parameters: |
| 302 |
if parameter.is_set: |
| 303 |
# This will include a trailing space: |
| 304 |
commandline += str(parameter) |
| 305 |
return commandline.strip() # remove trailing space |
| 306 |
|
| 307 |
def __repr__(self): |
| 308 |
"""Return a representation of the command line object for debugging. |
| 309 |
e.g. |
| 310 |
>>> from Bio.Emboss.Applications import WaterCommandline |
| 311 |
>>> cline = WaterCommandline(gapopen=10, gapextend=0.5) |
| 312 |
>>> cline.asequence = "asis:ACCCGGGCGCGGT" |
| 313 |
>>> cline.bsequence = "asis:ACCCGAGCGCGGT" |
| 314 |
>>> cline.outfile = "temp_water.txt" |
| 315 |
>>> print(cline) |
| 316 |
water -outfile=temp_water.txt -asequence=asis:ACCCGGGCGCGGT |
| 317 |
-bsequence=asis:ACCCGAGCGCGGT -gapopen=10 -gapextend=0.5 |
| 318 |
>>> cline |
| 319 |
WaterCommandline(cmd='water', outfile='temp_water.txt', |
| 320 |
asequence='asis:ACCCGGGCGCGGT', |
| 321 |
bsequence='asis:ACCCGAGCGCGGT', |
| 322 |
gapopen=10, gapextend=0.5) |
| 323 |
""" |
| 324 |
if self.path_exec == "": |
| 325 |
answer = "%s(cmd=%r" % (self.__class__.__name__, |
| 326 |
self.program_name) |
| 327 |
else: |
| 328 |
answer = "%s(cmd=%r, path_executable=%r" % (self.__class__.__name__, |
| 329 |
self.program_name, |
| 330 |
self.path_exec) |
| 331 |
if self.language == "": |
| 332 |
answer = "%s" % answer |
| 333 |
else: |
| 334 |
answer = "%s, programming_language=%r" % (answer, self.language) |
| 335 |
for parameter in self.parameters: |
| 336 |
if parameter.is_set: |
| 337 |
if isinstance(parameter, _SwitchArgument): |
| 338 |
answer += ", %s=True" % parameter.names[-1] |
| 339 |
else: |
| 340 |
answer += ", %s=%r" % (parameter.names[-1], |
| 341 |
parameter.value) |
| 342 |
answer += ")" |
| 343 |
return answer |
| 344 |
|
| 345 |
def _get_parameter(self, name): |
| 346 |
"""Get a commandline option value (PRIVATE).""" |
| 347 |
for parameter in self.parameters: |
| 348 |
if name in parameter.names: |
| 349 |
if isinstance(parameter, _SwitchArgument): |
| 350 |
return parameter.is_set |
| 351 |
else: |
| 352 |
if parameter.is_set: |
| 353 |
return parameter.value |
| 354 |
else: |
| 355 |
if parameter.default is not None: |
| 356 |
return str(parameter.default) + " (default)" |
| 357 |
else: |
| 358 |
raise ValueError("Option name %s is not set and" |
| 359 |
" does not have a default value." |
| 360 |
% name) |
| 361 |
raise ValueError("Option name %s was not found." % name) |
| 362 |
|
| 363 |
def _clear_parameter(self, name): |
| 364 |
"""Reset or clear a commandline option value (PRIVATE).""" |
| 365 |
cleared_option = False |
| 366 |
for parameter in self.parameters: |
| 367 |
if name in parameter.names: |
| 368 |
parameter.value = None |
| 369 |
parameter.is_set = False |
| 370 |
cleared_option = True |
| 371 |
if not cleared_option: |
| 372 |
raise ValueError("Option name %s was not found." % name) |
| 373 |
|
| 374 |
def set_parameter(self, name, value=None): |
| 375 |
"""Set a commandline option for a program (OBSOLETE). |
| 376 |
Every parameter is available via a property and as a named |
| 377 |
keyword when creating the instance. Using either of these is |
| 378 |
preferred to this legacy set_parameter method which is now |
| 379 |
OBSOLETE, and likely to be DEPRECATED and later REMOVED in |
| 380 |
future releases. |
| 381 |
""" |
| 382 |
set_option = False |
| 383 |
for parameter in self.parameters: |
| 384 |
if name in parameter.names: |
| 385 |
if isinstance(parameter, _SwitchArgument): |
| 386 |
if value is None: |
| 387 |
import warnings |
| 388 |
|
| 389 |
warnings.warn( |
| 390 |
"For a switch type argument like %s, " |
| 391 |
"we expect a boolean. None is treated " |
| 392 |
"as FALSE!" % parameter.names[-1] |
| 393 |
) |
| 394 |
parameter.is_set = bool(value) |
| 395 |
set_option = True |
| 396 |
elif isinstance(parameter, _SwitchValueArgument): |
| 397 |
if value is None: |
| 398 |
import warnings |
| 399 |
|
| 400 |
warnings.warn( |
| 401 |
"For a switch type argument like %s, " |
| 402 |
"we expect a boolean. None is treated " |
| 403 |
"as FALSE!" % parameter.names[-1] |
| 404 |
) |
| 405 |
elif isinstance(value, bool): |
| 406 |
parameter.is_set = bool(value) |
| 407 |
else: |
| 408 |
self._check_value(value, name, |
| 409 |
parameter.checker_function) |
| 410 |
parameter.value = value |
| 411 |
parameter.is_set = True |
| 412 |
set_option = True |
| 413 |
else: |
| 414 |
if value is not None: |
| 415 |
self._check_value(value, name, |
| 416 |
parameter.checker_function) |
| 417 |
parameter.value = value |
| 418 |
parameter.is_set = True |
| 419 |
set_option = True |
| 420 |
if not set_option: |
| 421 |
param_lst = [str(x.names) for x in self.parameters] |
| 422 |
raise ValueError("""Argument with name '%s' was not found among |
| 423 |
the different arguments for %s, which are: %s. |
| 424 |
Use 'custom_args' if your argument is not in |
| 425 |
the previous list.""" % ( |
| 426 |
name, self.program_name, ", ".join(param_lst))) |
| 427 |
|
| 428 |
def _check_value(self, value, name, check_function): |
| 429 |
"""Check whether the given value is valid (PRIVATE). |
| 430 |
No return value - it either works or raises a ValueError. |
| 431 |
This uses the passed function 'check_function', which can either |
| 432 |
return a [0, 1] (bad, good) value or raise an error. Either way |
| 433 |
this function will raise an error if the value is not valid, or |
| 434 |
finish silently otherwise. |
| 435 |
""" |
| 436 |
if check_function is not None: |
| 437 |
is_good = check_function(value) # May raise an exception |
| 438 |
if is_good not in [0, 1, True, False]: |
| 439 |
raise ValueError( |
| 440 |
"Result of check_function: %r is of an unexpected value" |
| 441 |
% is_good |
| 442 |
) |
| 443 |
if not is_good: |
| 444 |
raise ValueError( |
| 445 |
"Invalid parameter value %r for parameter %s" |
| 446 |
% (value, name) |
| 447 |
) |
| 448 |
|
| 449 |
def __setattr__(self, name, value): |
| 450 |
"""Set attribute name to value (PRIVATE). |
| 451 |
This code implements a workaround for a user interface issue. |
| 452 |
Without this __setattr__ attribute-based assignment of parameters |
| 453 |
will silently accept invalid parameters, leading to known instances |
| 454 |
of the user assuming that parameters for the application are set, |
| 455 |
when they are not. |
| 456 |
>>> from Bio.Emboss.Applications import WaterCommandline |
| 457 |
>>> cline = WaterCommandline(gapopen=10, gapextend=0.5, stdout=True) |
| 458 |
>>> cline.asequence = "a.fasta" |
| 459 |
>>> cline.bsequence = "b.fasta" |
| 460 |
>>> cline.csequence = "c.fasta" |
| 461 |
Traceback (most recent call last): |
| 462 |
... |
| 463 |
ValueError: Option name csequence was not found. |
| 464 |
>>> print(cline) |
| 465 |
water -stdout -asequence=a.fasta -bsequence=b.fasta -gapopen=10 |
| 466 |
-gapextend=0.5 |
| 467 |
This workaround uses a whitelist of object attributes, and sets the |
| 468 |
object attribute list as normal, for these. Other attributes are |
| 469 |
assumed to be parameters, and passed to the self.set_parameter method |
| 470 |
for validation and assignment. |
| 471 |
""" |
| 472 |
if name in CommandLineBase.allowed_attr: # Allowed attributes |
| 473 |
self.__dict__[name] = value |
| 474 |
else: |
| 475 |
self.set_parameter(name, value) # treat as a parameter |
| 476 |
|
| 477 |
def __call__(self, stdin=None, stdout=True, stderr=True, cwd=None, |
| 478 |
env=None): |
| 479 |
"""Execute command, wait for it to finish, return (stdout, stderr). |
| 480 |
Runs the command line tool and waits for it to finish. If it returns |
| 481 |
a non-zero error level, an exception is raised. Otherwise two strings |
| 482 |
are returned containing stdout and stderr. |
| 483 |
The optional stdin argument should be a string of data which will be |
| 484 |
passed to the tool as standard input. |
| 485 |
The optional stdout and stderr argument may be filenames (string), |
| 486 |
but otherwise are treated as a booleans, and control if the output |
| 487 |
should be captured as strings (True, default), or ignored by sending |
| 488 |
it to /dev/null to avoid wasting memory (False). If sent to a file |
| 489 |
or ignored, then empty string(s) are returned. |
| 490 |
The optional cwd argument is a string giving the working directory |
| 491 |
to run the command from. See Python's subprocess module documentation |
| 492 |
for more details. |
| 493 |
The optional env argument is a dictionary setting the environment |
| 494 |
variables to be used in the new process. By default the current |
| 495 |
process' environment variables are used. See Python's subprocess |
| 496 |
module documentation for more details. |
| 497 |
Default example usage:: |
| 498 |
from Bio.Emboss.Applications import WaterCommandline |
| 499 |
water_cmd = WaterCommandline(gapopen=10, gapextend=0.5, |
| 500 |
stdout=True, auto=True, |
| 501 |
asequence="a.fasta", |
| 502 |
bsequence="b.fasta") |
| 503 |
print("About to run: %s" % water_cmd) |
| 504 |
std_output, err_output = water_cmd() |
| 505 |
This functionality is similar to subprocess.check_output(). In general |
| 506 |
if you require more control over running the command, use subprocess |
| 507 |
directly. |
| 508 |
When the program called returns a non-zero error level, a custom |
| 509 |
ApplicationError exception is raised. This includes any stdout and |
| 510 |
stderr strings captured as attributes of the exception object, since |
| 511 |
they may be useful for diagnosing what went wrong. |
| 512 |
""" |
| 513 |
if not stdout: |
| 514 |
stdout_arg = open(os.devnull, "w") |
| 515 |
elif isinstance(stdout, str): |
| 516 |
stdout_arg = open(stdout, "w") |
| 517 |
else: |
| 518 |
stdout_arg = subprocess.PIPE |
| 519 |
|
| 520 |
if not stderr: |
| 521 |
stderr_arg = open(os.devnull, "w") |
| 522 |
elif isinstance(stderr, str): |
| 523 |
if stdout == stderr: |
| 524 |
stderr_arg = stdout_arg # Write both to the same file |
| 525 |
else: |
| 526 |
stderr_arg = open(stderr, "w") |
| 527 |
else: |
| 528 |
stderr_arg = subprocess.PIPE |
| 529 |
|
| 530 |
if sys.platform != "win32": |
| 531 |
use_shell = True |
| 532 |
else: |
| 533 |
win_ver = platform.win32_ver()[0] |
| 534 |
if win_ver in ["7", "8", "post2012Server", "10"]: |
| 535 |
use_shell = True |
| 536 |
else: |
| 537 |
use_shell = False |
| 538 |
child_process = subprocess.Popen( |
| 539 |
str(self), |
| 540 |
stdin=subprocess.PIPE, |
| 541 |
stdout=stdout_arg, |
| 542 |
stderr=stderr_arg, |
| 543 |
universal_newlines=True, |
| 544 |
cwd=cwd, |
| 545 |
env=env, |
| 546 |
shell=use_shell, |
| 547 |
) |
| 548 |
# Use .communicate as can get deadlocks with .wait(), see Bug 2804 |
| 549 |
stdout_str, stderr_str = child_process.communicate(stdin) |
| 550 |
if not stdout: |
| 551 |
assert not stdout_str, stdout_str |
| 552 |
if not stderr: |
| 553 |
assert not stderr_str, stderr_str |
| 554 |
return_code = child_process.returncode |
| 555 |
|
| 556 |
# Particularly important to close handles on Jython and PyPy |
| 557 |
# (where garbage collection is less predictable) and on Windows |
| 558 |
# (where cannot delete files with an open handle): |
| 559 |
if not stdout or isinstance(stdout, str): |
| 560 |
# We opened /dev/null or a file |
| 561 |
stdout_arg.close() |
| 562 |
if not stderr or (isinstance(stderr, str) and stdout != stderr): |
| 563 |
# We opened /dev/null or a file |
| 564 |
stderr_arg.close() |
| 565 |
|
| 566 |
if return_code: |
| 567 |
raise ApplicationError(return_code, str(self), stdout_str, |
| 568 |
stderr_str) |
| 569 |
return stdout_str, stderr_str |
| 570 |
|
| 571 |
|
| 572 |
class _ArgumentBase: |
| 573 |
"""A class to hold information about a parameter for a commandline. |
| 574 |
Do not use this directly, instead use one of the subclasses. |
| 575 |
""" |
| 576 |
|
| 577 |
def __init__(self): |
| 578 |
raise NotImplementedError |
| 579 |
|
| 580 |
def __str__(self): |
| 581 |
raise NotImplementedError |
| 582 |
|
| 583 |
|
| 584 |
class _ContentArgument(_ArgumentBase): |
| 585 |
"""Represent an option that can be set for a program. |
| 586 |
This holds UNIXish options like --append=yes and -a yes, |
| 587 |
where a value (here "yes") is generally expected. |
| 588 |
For UNIXish options like -kimura in clustalw which don't |
| 589 |
take a value, use the _SwitchArgument object instead. |
| 590 |
Attributes: |
| 591 |
- names -- a list of string names (typically two entries) by which |
| 592 |
the parameter can be set via the legacy set_parameter method |
| 593 |
(eg ["-a", "--append", "append"]). The first name in list is used |
| 594 |
when building the command line. The last name in the list is a |
| 595 |
"human readable" name describing the option in one word. This |
| 596 |
must be a valid Python identifier as it is used as the property |
| 597 |
name and as a keyword argument, and should therefore follow PEP8 |
| 598 |
naming. |
| 599 |
- description -- a description of the option. This is used as |
| 600 |
the property docstring. |
| 601 |
- filename -- True if this argument is a filename (or other argument |
| 602 |
that should be quoted) and should be automatically quoted if it |
| 603 |
contains spaces. |
| 604 |
- checker_function -- a reference to a function that will determine |
| 605 |
if a given value is valid for this parameter. This function can either |
| 606 |
raise an error when given a bad value, or return a [0, 1] decision on |
| 607 |
whether the value is correct. |
| 608 |
- equate -- should an equals sign be inserted if a value is used? |
| 609 |
- is_required -- a flag to indicate if the parameter must be set for |
| 610 |
the program to be run. |
| 611 |
- is_set -- if the parameter has been set |
| 612 |
- value -- the value of a parameter |
| 613 |
""" |
| 614 |
|
| 615 |
def __init__( |
| 616 |
self, |
| 617 |
names, |
| 618 |
description, |
| 619 |
filename=False, |
| 620 |
checker_function=None, |
| 621 |
is_required=False, |
| 622 |
equate=False, |
| 623 |
required_options=None, |
| 624 |
alter_options=None, |
| 625 |
incompatible=None, |
| 626 |
allow_multiple=False, |
| 627 |
default=None |
| 628 |
): |
| 629 |
self.names = names |
| 630 |
if not isinstance(description, str): |
| 631 |
raise TypeError("Should be a string: %r for %s" % (description, names[-1])) |
| 632 |
# Note 'filename' is for any string with spaces that needs quoting |
| 633 |
self.is_filename = filename |
| 634 |
self.checker_function = checker_function |
| 635 |
self.description = description |
| 636 |
self.equate = equate |
| 637 |
self.is_required = is_required |
| 638 |
self.is_set = False |
| 639 |
self.value = None |
| 640 |
self.required_options = required_options |
| 641 |
self.alter_options = alter_options |
| 642 |
self.incompatible = incompatible |
| 643 |
self.default = default |
| 644 |
self.allow_multiple = allow_multiple |
| 645 |
|
| 646 |
def __str__(self): |
| 647 |
"""Return the value of this option for the commandline. |
| 648 |
Includes a trailing space. |
| 649 |
""" |
| 650 |
# Note: Before equate was handled explicitly, the old |
| 651 |
# code would do either "--name " or "--name=value ", |
| 652 |
# or " -name " or " -name value ". This choice is now |
| 653 |
# now made explicitly when setting up the option. |
| 654 |
if self.value is None: |
| 655 |
return "%s " % self.names[0] |
| 656 |
if isinstance(self.value, list): |
| 657 |
if self.allow_multiple: |
| 658 |
if self.is_filename: |
| 659 |
v = " ".join(_escape_filename(val) for val in self.value) + " " |
| 660 |
else: |
| 661 |
v = " '" + " ".join(self.value) + "' " |
| 662 |
else: |
| 663 |
raise TypeError("This argument cannot be a list") |
| 664 |
else: |
| 665 |
if self.is_filename: |
| 666 |
v = _escape_filename(self.value) |
| 667 |
else: |
| 668 |
v = str(self.value) |
| 669 |
if self.equate: |
| 670 |
return "%s=%s " % (self.names[0], v) |
| 671 |
else: |
| 672 |
return "%s %s " % (self.names[0], v) |
| 673 |
|
| 674 |
|
| 675 |
class _SwitchValueArgument(_ArgumentBase): |
| 676 |
"""Represent an optional argument switcht that can introduce a value for a |
| 677 |
program. This holds UNIXish options like -proxi in kma can either be |
| 678 |
included in the command string or ommitted; and when included, can have a |
| 679 |
value or not. |
| 680 |
Attributes: |
| 681 |
- names -- a list of string names (typically two entries) by which |
| 682 |
the parameter can be set via the legacy set_parameter method |
| 683 |
(eg ["-a", "--append", "append"]). The first name in list is used |
| 684 |
when building the command line. The last name in the list is a |
| 685 |
"human readable" name describing the option in one word. This |
| 686 |
must be a valid Python identifier as it is used as the property |
| 687 |
name and as a keyword argument, and should therefore follow PEP8 |
| 688 |
naming. |
| 689 |
- description -- a description of the option. This is used as |
| 690 |
the property docstring. |
| 691 |
- filename -- True if this argument is a filename (or other argument |
| 692 |
that should be quoted) and should be automatically quoted if it |
| 693 |
contains spaces. |
| 694 |
- checker_function -- a reference to a function that will determine |
| 695 |
if a given value is valid for this parameter. This function can either |
| 696 |
raise an error when given a bad value, or return a [0, 1] decision on |
| 697 |
whether the value is correct. |
| 698 |
- equate -- should an equals sign be inserted if a value is used? |
| 699 |
- is_required -- a flag to indicate if the parameter must be set for |
| 700 |
the program to be run. |
| 701 |
- is_set -- if the parameter has been set |
| 702 |
- value -- the value of a parameter""" |
| 703 |
|
| 704 |
def __init__( |
| 705 |
self, |
| 706 |
names, |
| 707 |
description, |
| 708 |
filename=False, |
| 709 |
checker_function=None, |
| 710 |
is_required=False, |
| 711 |
equate=False, |
| 712 |
default=False, |
| 713 |
incompatible=None, |
| 714 |
): |
| 715 |
self.names = names |
| 716 |
if not isinstance(description, str): |
| 717 |
raise TypeError("Should be a string: %r for %s" % (description, |
| 718 |
names[-1])) |
| 719 |
# Note 'filename' is for any string with spaces that needs quoting |
| 720 |
self.is_filename = filename |
| 721 |
self.checker_function = checker_function |
| 722 |
self.description = description |
| 723 |
self.equate = equate |
| 724 |
self.is_required = is_required |
| 725 |
self.is_set = False |
| 726 |
self.value = None |
| 727 |
self.default = default |
| 728 |
self.incompatible = incompatible |
| 729 |
|
| 730 |
def __str__(self): |
| 731 |
"""Return the value of this option for the commandline. |
| 732 |
Includes a trailing space. |
| 733 |
""" |
| 734 |
# Note: Before equate was handled explicitly, the old |
| 735 |
# code would do either "--name " or "--name=value ", |
| 736 |
# or " -name " or " -name value ". This choice is now |
| 737 |
# now made explicitly when setting up the option. |
| 738 |
if not self.is_set: |
| 739 |
return "%s False" % self.names[0] |
| 740 |
if self.value is None: |
| 741 |
return "%s " % (self.names[0]) |
| 742 |
if self.is_filename: |
| 743 |
v = _escape_filename(self.value) |
| 744 |
else: |
| 745 |
v = str(self.value) |
| 746 |
if self.equate: |
| 747 |
return "%s=%s " % (self.names[0], v) |
| 748 |
else: |
| 749 |
return "%s %s " % (self.names[0], v) |
| 750 |
|
| 751 |
|
| 752 |
class _SwitchArgument(_ArgumentBase): |
| 753 |
"""Represent an optional argument switch for a program. |
| 754 |
This holds UNIXish options like -kimura in clustalw which don't |
| 755 |
take a value, they are either included in the command string |
| 756 |
or omitted. |
| 757 |
Attributes: |
| 758 |
- names -- a list of string names (typically two entries) by which |
| 759 |
the parameter can be set via the legacy set_parameter method |
| 760 |
(eg ["-a", "--append", "append"]). The first name in list is used |
| 761 |
when building the command line. The last name in the list is a |
| 762 |
"human readable" name describing the option in one word. This |
| 763 |
must be a valid Python identifier as it is used as the property |
| 764 |
name and as a keyword argument, and should therefore follow PEP8 |
| 765 |
naming. |
| 766 |
- description -- a description of the option. This is used as |
| 767 |
the property docstring. |
| 768 |
- is_set -- if the parameter has been set |
| 769 |
- no_run -- if the argument exits the program |
| 770 |
NOTE - There is no value attribute, see is_set instead, |
| 771 |
""" |
| 772 |
|
| 773 |
def __init__(self, names, description, default=False, no_run=False, |
| 774 |
incompatible=None): |
| 775 |
self.names = names |
| 776 |
self.description = description |
| 777 |
self.is_set = False |
| 778 |
self.is_required = False |
| 779 |
self.no_run = no_run |
| 780 |
self.default = default |
| 781 |
self.incompatible = incompatible |
| 782 |
|
| 783 |
def __str__(self): |
| 784 |
"""Return the value of this option for the commandline. |
| 785 |
Includes a trailing space. |
| 786 |
""" |
| 787 |
assert not hasattr(self, "value") |
| 788 |
if self.is_set: |
| 789 |
return "%s " % self.names[0] |
| 790 |
else: |
| 791 |
return "" |
| 792 |
|
| 793 |
|
| 794 |
class _Argument(_ArgumentBase): |
| 795 |
"""Represent an argument on a commandline. |
| 796 |
The names argument should be a list containing one string. |
| 797 |
This must be a valid Python identifier as it is used as the |
| 798 |
property name and as a keyword argument, and should therefore |
| 799 |
follow PEP8 naming. |
| 800 |
""" |
| 801 |
|
| 802 |
def __init__( |
| 803 |
self, |
| 804 |
names, |
| 805 |
description, |
| 806 |
filename=False, |
| 807 |
checker_function=None, |
| 808 |
is_required=False, |
| 809 |
): |
| 810 |
self.names = names |
| 811 |
if not isinstance(description, str): |
| 812 |
raise TypeError("Should be a string: %r for %s" % (description, |
| 813 |
names[-1])) |
| 814 |
# Note 'filename' is for any string with spaces that needs quoting |
| 815 |
self.is_filename = filename |
| 816 |
self.checker_function = checker_function |
| 817 |
self.description = description |
| 818 |
self.is_required = is_required |
| 819 |
self.is_set = False |
| 820 |
self.value = None |
| 821 |
self.no_run = False |
| 822 |
|
| 823 |
def __str__(self): |
| 824 |
if self.value is None: |
| 825 |
return " " |
| 826 |
elif self.is_filename: |
| 827 |
return "%s " % _escape_filename(self.value) |
| 828 |
else: |
| 829 |
return "%s " % self.value |
| 830 |
|
| 831 |
|
| 832 |
class _ArgumentList(_Argument): |
| 833 |
"""Represent a variable list of arguments on a command line, e.g. multiple |
| 834 |
filenames.""" |
| 835 |
|
| 836 |
# TODO - Option to require at least one value? e.g. min/max count? |
| 837 |
|
| 838 |
def __str__(self): |
| 839 |
if not isinstance(self.value, list): |
| 840 |
raise TypeError("Arguments should be a list") |
| 841 |
if not self.value: |
| 842 |
raise ValueError("Requires at least one filename") |
| 843 |
# A trailing space is required so that parameters following the last filename |
| 844 |
# do not appear merged. |
| 845 |
# e.g.: samtools cat in1.bam in2.bam-o out.sam [without trailing space][Incorrect] |
| 846 |
# samtools cat in1.bam in2.bam -o out.sam [with trailing space][Correct] |
| 847 |
if self.is_filename: |
| 848 |
return " ".join(_escape_filename(v) for v in self.value) + " " |
| 849 |
else: |
| 850 |
return " ".join(self.value) + " " |
| 851 |
|
| 852 |
|
| 853 |
class _StaticArgument(_ArgumentBase): |
| 854 |
"""Represent a static (read only) argument on a commandline. |
| 855 |
This is not intended to be exposed as a named argument or |
| 856 |
property of a command line wrapper object. |
| 857 |
""" |
| 858 |
|
| 859 |
def __init__(self, value): |
| 860 |
self.names = [] |
| 861 |
self.is_required = False |
| 862 |
self.is_set = True |
| 863 |
self.value = value |
| 864 |
|
| 865 |
def __str__(self): |
| 866 |
return "%s " % self.value |
| 867 |
|
| 868 |
|
| 869 |
def _escape_filename(filename): |
| 870 |
"""Escape filenames with spaces by adding quotes (PRIVATE). |
| 871 |
Note this will not add quotes if they are already included: |
| 872 |
>>> print((_escape_filename('example with spaces'))) |
| 873 |
"example with spaces" |
| 874 |
>>> print((_escape_filename('"example with spaces"'))) |
| 875 |
"example with spaces" |
| 876 |
>>> print((_escape_filename(1))) |
| 877 |
1 |
| 878 |
Note the function is more generic than the name suggests, since it |
| 879 |
is used to add quotes around any string arguments containing spaces. |
| 880 |
""" |
| 881 |
|
| 882 |
if not isinstance(filename, str): |
| 883 |
# for example the NCBI BLAST+ -outfmt argument can be an integer |
| 884 |
return filename |
| 885 |
if " " not in filename: |
| 886 |
return filename |
| 887 |
# We'll just quote it - works on Windows, Mac OS X etc |
| 888 |
if filename.startswith('"') and filename.endswith('"'): |
| 889 |
# Its already quoted |
| 890 |
return filename |
| 891 |
else: |
| 892 |
return '"%s"' % filename |
| 893 |
|
| 894 |
|
| 895 |
def _test(): |
| 896 |
"""Run the Bio.Application module's doctests (PRIVATE).""" |
| 897 |
import doctest |
| 898 |
|
| 899 |
doctest.testmod(verbose=1) |
| 900 |
|
| 901 |
|
| 902 |
if __name__ == "__main__": |
| 903 |
# Run the doctests |
| 904 |
_test() |