PageRenderTime 34ms CodeModel.GetById 0ms RepoModel.GetById 1ms app.codeStats 0ms

/Bio/Application/__init__.py

https://gitlab.com/18runt88/biopython
Python | 755 lines | 715 code | 7 blank | 33 comment | 10 complexity | 16ab8ff438e9cfd1b0fe0b71d7f80e29 MD5 | raw file
  1. # Copyright 2001-2004 Brad Chapman.
  2. # Revisions copyright 2009-2013 by Peter Cock.
  3. # All rights reserved.
  4. # This code is part of the Biopython distribution and governed by its
  5. # license. Please see the LICENSE file that should have been included
  6. # as part of this package.
  7. """General mechanisms to access applications in Biopython.
  8. This module is not intended for direct use. It provides the basic objects which
  9. are subclassed by our command line wrappers, such as:
  10. - Bio.Align.Applications
  11. - Bio.Blast.Applications
  12. - Bio.Emboss.Applications
  13. - Bio.Sequencing.Applications
  14. These modules provide wrapper classes for command line tools to help you
  15. construct command line strings by setting the values of each parameter.
  16. The finished command line strings are then normally invoked via the built-in
  17. Python module subprocess.
  18. """
  19. from __future__ import print_function
  20. from Bio._py3k import basestring
  21. import os
  22. import platform
  23. import sys
  24. import subprocess
  25. import re
  26. from subprocess import CalledProcessError as _ProcessCalledError
  27. from Bio import File
  28. __docformat__ = "restructuredtext en"
  29. # Use this regular expression to test the property names are going to
  30. # be valid as Python properties or arguments
  31. _re_prop_name = re.compile(r"^[a-zA-Z][a-zA-Z0-9_]*$")
  32. assert _re_prop_name.match("t")
  33. assert _re_prop_name.match("test")
  34. assert _re_prop_name.match("_test") is None # we don't want private names
  35. assert _re_prop_name.match("-test") is None
  36. assert _re_prop_name.match("any-hyphen") is None
  37. assert _re_prop_name.match("underscore_ok")
  38. assert _re_prop_name.match("test_name")
  39. assert _re_prop_name.match("test2")
  40. # These are reserved names in Python itself,
  41. _reserved_names = ["and", "del", "from", "not", "while", "as", "elif",
  42. "global", "or", "with", "assert", "else", "if", "pass",
  43. "yield", "break", "except", "import", "print", "class",
  44. "exec", "in", "raise", "continue", "finally", "is",
  45. "return", "def", "for", "lambda", "try"]
  46. # These are reserved names due to the way the wrappers work
  47. _local_reserved_names = ["set_parameter"]
  48. class ApplicationError(_ProcessCalledError):
  49. """Raised when an application returns a non-zero exit status.
  50. The exit status will be stored in the returncode attribute, similarly
  51. the command line string used in the cmd attribute, and (if captured)
  52. stdout and stderr as strings.
  53. This exception is a subclass of subprocess.CalledProcessError.
  54. >>> err = ApplicationError(-11, "helloworld", "", "Some error text")
  55. >>> err.returncode, err.cmd, err.stdout, err.stderr
  56. (-11, 'helloworld', '', 'Some error text')
  57. >>> print(err)
  58. Non-zero return code -11 from 'helloworld', message 'Some error text'
  59. """
  60. def __init__(self, returncode, cmd, stdout="", stderr=""):
  61. self.returncode = returncode
  62. self.cmd = cmd
  63. self.stdout = stdout
  64. self.stderr = stderr
  65. def __str__(self):
  66. # get first line of any stderr message
  67. try:
  68. msg = self.stderr.lstrip().split("\n", 1)[0].rstrip()
  69. except Exception: # TODO, ValueError? AttributeError?
  70. msg = ""
  71. if msg:
  72. return "Non-zero return code %d from %r, message %r" \
  73. % (self.returncode, self.cmd, msg)
  74. else:
  75. return "Non-zero return code %d from %r" \
  76. % (self.returncode, self.cmd)
  77. def __repr__(self):
  78. return "ApplicationError(%i, %s, %s, %s)" \
  79. % (self.returncode, self.cmd, self.stdout, self.stderr)
  80. class AbstractCommandline(object):
  81. """Generic interface for constructing command line strings.
  82. This class shouldn't be called directly; it should be subclassed to
  83. provide an implementation for a specific application.
  84. For a usage example we'll show one of the EMBOSS wrappers. You can set
  85. options when creating the wrapper object using keyword arguments - or
  86. later using their corresponding properties:
  87. >>> from Bio.Emboss.Applications import WaterCommandline
  88. >>> cline = WaterCommandline(gapopen=10, gapextend=0.5)
  89. >>> cline
  90. WaterCommandline(cmd='water', gapopen=10, gapextend=0.5)
  91. You can instead manipulate the parameters via their properties, e.g.
  92. >>> cline.gapopen
  93. 10
  94. >>> cline.gapopen = 20
  95. >>> cline
  96. WaterCommandline(cmd='water', gapopen=20, gapextend=0.5)
  97. You can clear a parameter you have already added by 'deleting' the
  98. corresponding property:
  99. >>> del cline.gapopen
  100. >>> cline.gapopen
  101. >>> cline
  102. WaterCommandline(cmd='water', gapextend=0.5)
  103. Once you have set the parameters you need, you can turn the object into
  104. a string (e.g. to log the command):
  105. >>> str(cline)
  106. Traceback (most recent call last):
  107. ...
  108. ValueError: You must either set outfile (output filename), or enable filter or stdout (output to stdout).
  109. In this case the wrapper knows certain arguments are required to construct
  110. a valid command line for the tool. For a complete example,
  111. >>> from Bio.Emboss.Applications import WaterCommandline
  112. >>> water_cmd = WaterCommandline(gapopen=10, gapextend=0.5)
  113. >>> water_cmd.asequence = "asis:ACCCGGGCGCGGT"
  114. >>> water_cmd.bsequence = "asis:ACCCGAGCGCGGT"
  115. >>> water_cmd.outfile = "temp_water.txt"
  116. >>> print(water_cmd)
  117. water -outfile=temp_water.txt -asequence=asis:ACCCGGGCGCGGT -bsequence=asis:ACCCGAGCGCGGT -gapopen=10 -gapextend=0.5
  118. >>> water_cmd
  119. WaterCommandline(cmd='water', outfile='temp_water.txt', asequence='asis:ACCCGGGCGCGGT', bsequence='asis:ACCCGAGCGCGGT', gapopen=10, gapextend=0.5)
  120. You would typically run the command line via a standard Python operating
  121. system call using the subprocess module for full control. For the simple
  122. case where you just want to run the command and get the output:
  123. stdout, stderr = water_cmd()
  124. Note that by default we assume the underlying tool is installed on the
  125. system $PATH environment variable. This is normal under Linux/Unix, but
  126. may need to be done manually under Windows. Alternatively, you can specify
  127. the full path to the binary as the first argument (cmd):
  128. >>> from Bio.Emboss.Applications import WaterCommandline
  129. >>> water_cmd = WaterCommandline("C:\Program Files\EMBOSS\water.exe",
  130. ... gapopen=10, gapextend=0.5,
  131. ... asequence="asis:ACCCGGGCGCGGT",
  132. ... bsequence="asis:ACCCGAGCGCGGT",
  133. ... outfile="temp_water.txt")
  134. >>> print(water_cmd)
  135. "C:\Program Files\EMBOSS\water.exe" -outfile=temp_water.txt -asequence=asis:ACCCGGGCGCGGT -bsequence=asis:ACCCGAGCGCGGT -gapopen=10 -gapextend=0.5
  136. Notice that since the path name includes a space it has automatically
  137. been quoted.
  138. """
  139. # TODO - Replace the above example since EMBOSS doesn't work properly
  140. # if installed into a folder with a space like "C:\Program Files\EMBOSS"
  141. #
  142. # Note the call example above is not a doctest as we can't handle EMBOSS
  143. # (or any other tool) being missing in the unit tests.
  144. parameters = None # will be a list defined in subclasses
  145. def __init__(self, cmd, **kwargs):
  146. """Create a new instance of a command line wrapper object."""
  147. # Init method - should be subclassed!
  148. #
  149. # The subclass methods should look like this:
  150. #
  151. # def __init__(self, cmd="muscle", **kwargs):
  152. # self.parameters = [...]
  153. # AbstractCommandline.__init__(self, cmd, **kwargs)
  154. #
  155. # i.e. There should have an optional argument "cmd" to set the location
  156. # of the executable (with a sensible default which should work if the
  157. # command is on the path on Unix), and keyword arguments. It should
  158. # then define a list of parameters, all objects derived from the base
  159. # class _AbstractParameter.
  160. #
  161. # The keyword arguments should be any valid parameter name, and will
  162. # be used to set the associated parameter.
  163. self.program_name = cmd
  164. try:
  165. parameters = self.parameters
  166. except AttributeError:
  167. raise AttributeError("Subclass should have defined self.parameters")
  168. # Create properties for each parameter at run time
  169. aliases = set()
  170. for p in parameters:
  171. if not p.names:
  172. assert isinstance(p, _StaticArgument), p
  173. continue
  174. for name in p.names:
  175. if name in aliases:
  176. raise ValueError("Parameter alias %s multiply defined"
  177. % name)
  178. aliases.add(name)
  179. name = p.names[-1]
  180. if _re_prop_name.match(name) is None:
  181. raise ValueError("Final parameter name %s cannot be used as "
  182. "an argument or property name in python"
  183. % repr(name))
  184. if name in _reserved_names:
  185. raise ValueError("Final parameter name %s cannot be used as "
  186. "an argument or property name because it is "
  187. "a reserved word in python" % repr(name))
  188. if name in _local_reserved_names:
  189. raise ValueError("Final parameter name %s cannot be used as "
  190. "an argument or property name due to the "
  191. "way the AbstractCommandline class works"
  192. % repr(name))
  193. # Beware of binding-versus-assignment confusion issues
  194. def getter(name):
  195. return lambda x: x._get_parameter(name)
  196. def setter(name):
  197. return lambda x, value: x.set_parameter(name, value)
  198. def deleter(name):
  199. return lambda x: x._clear_parameter(name)
  200. doc = p.description
  201. if isinstance(p, _Switch):
  202. doc += "\n\nThis property controls the addition of the %s " \
  203. "switch, treat this property as a boolean." % p.names[0]
  204. else:
  205. doc += "\n\nThis controls the addition of the %s parameter " \
  206. "and its associated value. Set this property to the " \
  207. "argument value required." % p.names[0]
  208. prop = property(getter(name), setter(name), deleter(name), doc)
  209. setattr(self.__class__, name, prop) # magic!
  210. for key, value in kwargs.items():
  211. self.set_parameter(key, value)
  212. def _validate(self):
  213. """Make sure the required parameters have been set (PRIVATE).
  214. No return value - it either works or raises a ValueError.
  215. This is a separate method (called from __str__) so that subclasses may
  216. override it.
  217. """
  218. for p in self.parameters:
  219. # Check for missing required parameters:
  220. if p.is_required and not(p.is_set):
  221. raise ValueError("Parameter %s is not set."
  222. % p.names[-1])
  223. # Also repeat the parameter validation here, just in case?
  224. def __str__(self):
  225. """Make the commandline string with the currently set options.
  226. e.g.
  227. >>> from Bio.Emboss.Applications import WaterCommandline
  228. >>> cline = WaterCommandline(gapopen=10, gapextend=0.5)
  229. >>> cline.asequence = "asis:ACCCGGGCGCGGT"
  230. >>> cline.bsequence = "asis:ACCCGAGCGCGGT"
  231. >>> cline.outfile = "temp_water.txt"
  232. >>> print(cline)
  233. water -outfile=temp_water.txt -asequence=asis:ACCCGGGCGCGGT -bsequence=asis:ACCCGAGCGCGGT -gapopen=10 -gapextend=0.5
  234. >>> str(cline)
  235. 'water -outfile=temp_water.txt -asequence=asis:ACCCGGGCGCGGT -bsequence=asis:ACCCGAGCGCGGT -gapopen=10 -gapextend=0.5'
  236. """
  237. self._validate()
  238. commandline = "%s " % _escape_filename(self.program_name)
  239. for parameter in self.parameters:
  240. if parameter.is_set:
  241. # This will include a trailing space:
  242. commandline += str(parameter)
  243. return commandline.strip() # remove trailing space
  244. def __repr__(self):
  245. """Return a representation of the command line object for debugging.
  246. e.g.
  247. >>> from Bio.Emboss.Applications import WaterCommandline
  248. >>> cline = WaterCommandline(gapopen=10, gapextend=0.5)
  249. >>> cline.asequence = "asis:ACCCGGGCGCGGT"
  250. >>> cline.bsequence = "asis:ACCCGAGCGCGGT"
  251. >>> cline.outfile = "temp_water.txt"
  252. >>> print(cline)
  253. water -outfile=temp_water.txt -asequence=asis:ACCCGGGCGCGGT -bsequence=asis:ACCCGAGCGCGGT -gapopen=10 -gapextend=0.5
  254. >>> cline
  255. WaterCommandline(cmd='water', outfile='temp_water.txt', asequence='asis:ACCCGGGCGCGGT', bsequence='asis:ACCCGAGCGCGGT', gapopen=10, gapextend=0.5)
  256. """
  257. answer = "%s(cmd=%s" % (self.__class__.__name__, repr(self.program_name))
  258. for parameter in self.parameters:
  259. if parameter.is_set:
  260. if isinstance(parameter, _Switch):
  261. answer += ", %s=True" % parameter.names[-1]
  262. else:
  263. answer += ", %s=%s" \
  264. % (parameter.names[-1], repr(parameter.value))
  265. answer += ")"
  266. return answer
  267. def _get_parameter(self, name):
  268. """Get a commandline option value."""
  269. for parameter in self.parameters:
  270. if name in parameter.names:
  271. if isinstance(parameter, _Switch):
  272. return parameter.is_set
  273. else:
  274. return parameter.value
  275. raise ValueError("Option name %s was not found." % name)
  276. def _clear_parameter(self, name):
  277. """Reset or clear a commandline option value."""
  278. cleared_option = False
  279. for parameter in self.parameters:
  280. if name in parameter.names:
  281. parameter.value = None
  282. parameter.is_set = False
  283. cleared_option = True
  284. if not cleared_option:
  285. raise ValueError("Option name %s was not found." % name)
  286. def set_parameter(self, name, value=None):
  287. """Set a commandline option for a program (OBSOLETE).
  288. Every parameter is available via a property and as a named
  289. keyword when creating the instance. Using either of these is
  290. preferred to this legacy set_parameter method which is now
  291. OBSOLETE, and likely to be DEPRECATED and later REMOVED in
  292. future releases.
  293. """
  294. set_option = False
  295. for parameter in self.parameters:
  296. if name in parameter.names:
  297. if isinstance(parameter, _Switch):
  298. if value is None:
  299. import warnings
  300. warnings.warn("For a switch type argument like %s, "
  301. "we expect a boolean. None is treated "
  302. "as FALSE!" % parameter.names[-1])
  303. parameter.is_set = bool(value)
  304. set_option = True
  305. else:
  306. if value is not None:
  307. self._check_value(value, name, parameter.checker_function)
  308. parameter.value = value
  309. parameter.is_set = True
  310. set_option = True
  311. if not set_option:
  312. raise ValueError("Option name %s was not found." % name)
  313. def _check_value(self, value, name, check_function):
  314. """Check whether the given value is valid.
  315. No return value - it either works or raises a ValueError.
  316. This uses the passed function 'check_function', which can either
  317. return a [0, 1] (bad, good) value or raise an error. Either way
  318. this function will raise an error if the value is not valid, or
  319. finish silently otherwise.
  320. """
  321. if check_function is not None:
  322. is_good = check_function(value) # May raise an exception
  323. assert is_good in [0, 1, True, False]
  324. if not is_good:
  325. raise ValueError("Invalid parameter value %r for parameter %s"
  326. % (value, name))
  327. def __setattr__(self, name, value):
  328. """Set attribute name to value (PRIVATE).
  329. This code implements a workaround for a user interface issue.
  330. Without this __setattr__ attribute-based assignment of parameters
  331. will silently accept invalid parameters, leading to known instances
  332. of the user assuming that parameters for the application are set,
  333. when they are not.
  334. >>> from Bio.Emboss.Applications import WaterCommandline
  335. >>> cline = WaterCommandline(gapopen=10, gapextend=0.5, stdout=True)
  336. >>> cline.asequence = "a.fasta"
  337. >>> cline.bsequence = "b.fasta"
  338. >>> cline.csequence = "c.fasta"
  339. Traceback (most recent call last):
  340. ...
  341. ValueError: Option name csequence was not found.
  342. >>> print(cline)
  343. water -stdout -asequence=a.fasta -bsequence=b.fasta -gapopen=10 -gapextend=0.5
  344. This workaround uses a whitelist of object attributes, and sets the
  345. object attribute list as normal, for these. Other attributes are
  346. assumed to be parameters, and passed to the self.set_parameter method
  347. for validation and assignment.
  348. """
  349. if name in ['parameters', 'program_name']: # Allowed attributes
  350. self.__dict__[name] = value
  351. else:
  352. self.set_parameter(name, value) # treat as a parameter
  353. def __call__(self, stdin=None, stdout=True, stderr=True,
  354. cwd=None, env=None):
  355. """Executes the command, waits for it to finish, and returns output.
  356. Runs the command line tool and waits for it to finish. If it returns
  357. a non-zero error level, an exception is raised. Otherwise two strings
  358. are returned containing stdout and stderr.
  359. The optional stdin argument should be a string of data which will be
  360. passed to the tool as standard input.
  361. The optional stdout and stderr argument may be filenames (string),
  362. but otherwise are treated as a booleans, and control if the output
  363. should be captured as strings (True, default), or ignored by sending
  364. it to /dev/null to avoid wasting memory (False). If sent to a file
  365. or ignored, then empty string(s) are returned.
  366. The optional cwd argument is a string giving the working directory
  367. to run the command from. See Python's subprocess module documentation
  368. for more details.
  369. The optional env argument is a dictionary setting the environment
  370. variables to be used in the new process. By default the current
  371. process' environment variables are used. See Python's subprocess
  372. module documentation for more details.
  373. Default example usage::
  374. from Bio.Emboss.Applications import WaterCommandline
  375. water_cmd = WaterCommandline(gapopen=10, gapextend=0.5,
  376. stdout=True, auto=True,
  377. asequence="a.fasta", bsequence="b.fasta")
  378. print("About to run: %s" % water_cmd)
  379. std_output, err_output = water_cmd()
  380. This functionality is similar to subprocess.check_output() added in
  381. Python 2.7. In general if you require more control over running the
  382. command, use subprocess directly.
  383. As of Biopython 1.56, when the program called returns a non-zero error
  384. level, a custom ApplicationError exception is raised. This includes
  385. any stdout and stderr strings captured as attributes of the exception
  386. object, since they may be useful for diagnosing what went wrong.
  387. """
  388. if not stdout:
  389. stdout_arg = open(os.devnull, "w")
  390. elif isinstance(stdout, basestring):
  391. stdout_arg = open(stdout, "w")
  392. else:
  393. stdout_arg = subprocess.PIPE
  394. if not stderr:
  395. stderr_arg = open(os.devnull, "w")
  396. elif isinstance(stderr, basestring):
  397. if stdout == stderr:
  398. stderr_arg = stdout_arg # Write both to the same file
  399. else:
  400. stderr_arg = open(stderr, "w")
  401. else:
  402. stderr_arg = subprocess.PIPE
  403. # We may not need to supply any piped input, but we setup the
  404. # standard input pipe anyway as a work around for a python
  405. # bug if this is called from a Windows GUI program. For
  406. # details, see http://bugs.python.org/issue1124861
  407. #
  408. # Using universal newlines is important on Python 3, this
  409. # gives unicode handles rather than bytes handles.
  410. # Windows 7, 8 and 8.1 want shell = True
  411. # TODO: Test under Windows 10 and revisit platform detection.
  412. if sys.platform != "win32":
  413. use_shell = True
  414. else:
  415. win_ver = platform.win32_ver()[0]
  416. if win_ver in ["7", "8", "post2012Server"]:
  417. use_shell = True
  418. else:
  419. use_shell = False
  420. child_process = subprocess.Popen(str(self), stdin=subprocess.PIPE,
  421. stdout=stdout_arg, stderr=stderr_arg,
  422. universal_newlines=True,
  423. cwd=cwd, env=env,
  424. shell=use_shell)
  425. # Use .communicate as can get deadlocks with .wait(), see Bug 2804
  426. stdout_str, stderr_str = child_process.communicate(stdin)
  427. if not stdout:
  428. assert not stdout_str, stdout_str
  429. if not stderr:
  430. assert not stderr_str, stderr_str
  431. return_code = child_process.returncode
  432. # Particularly important to close handles on Jython and PyPy
  433. # (where garbage collection is less predictable) and on Windows
  434. # (where cannot delete files with an open handle):
  435. if not stdout or isinstance(stdout, basestring):
  436. # We opened /dev/null or a file
  437. stdout_arg.close()
  438. if not stderr or (isinstance(stderr, basestring) and stdout != stderr):
  439. # We opened /dev/null or a file
  440. stderr_arg.close()
  441. if return_code:
  442. raise ApplicationError(return_code, str(self),
  443. stdout_str, stderr_str)
  444. return stdout_str, stderr_str
  445. class _AbstractParameter(object):
  446. """A class to hold information about a parameter for a commandline.
  447. Do not use this directly, instead use one of the subclasses.
  448. """
  449. def __init__(self):
  450. raise NotImplementedError
  451. def __str__(self):
  452. raise NotImplementedError
  453. class _Option(_AbstractParameter):
  454. """Represent an option that can be set for a program.
  455. This holds UNIXish options like --append=yes and -a yes,
  456. where a value (here "yes") is generally expected.
  457. For UNIXish options like -kimura in clustalw which don't
  458. take a value, use the _Switch object instead.
  459. Attributes:
  460. o names -- a list of string names (typically two entries) by which
  461. the parameter can be set via the legacy set_parameter method
  462. (eg ["-a", "--append", "append"]). The first name in list is used
  463. when building the command line. The last name in the list is a
  464. "human readable" name describing the option in one word. This
  465. must be a valid Python identifier as it is used as the property
  466. name and as a keyword argument, and should therefore follow PEP8
  467. naming.
  468. o description -- a description of the option. This is used as
  469. the property docstring.
  470. o filename -- True if this argument is a filename and should be
  471. automatically quoted if it contains spaces.
  472. o checker_function -- a reference to a function that will determine
  473. if a given value is valid for this parameter. This function can either
  474. raise an error when given a bad value, or return a [0, 1] decision on
  475. whether the value is correct.
  476. o equate -- should an equals sign be inserted if a value is used?
  477. o is_required -- a flag to indicate if the parameter must be set for
  478. the program to be run.
  479. o is_set -- if the parameter has been set
  480. o value -- the value of a parameter
  481. """
  482. def __init__(self, names, description, filename=False, checker_function=None,
  483. is_required=False, equate=True):
  484. self.names = names
  485. assert isinstance(description, basestring), \
  486. "%r for %s" % (description, names[-1])
  487. self.is_filename = filename
  488. self.checker_function = checker_function
  489. self.description = description
  490. self.equate = equate
  491. self.is_required = is_required
  492. self.is_set = False
  493. self.value = None
  494. def __str__(self):
  495. """Return the value of this option for the commandline.
  496. Includes a trailing space.
  497. """
  498. # Note: Before equate was handled explicitly, the old
  499. # code would do either "--name " or "--name=value ",
  500. # or " -name " or " -name value ". This choice is now
  501. # now made explicitly when setting up the option.
  502. if self.value is None:
  503. return "%s " % self.names[0]
  504. if self.is_filename:
  505. v = _escape_filename(self.value)
  506. else:
  507. v = str(self.value)
  508. if self.equate:
  509. return "%s=%s " % (self.names[0], v)
  510. else:
  511. return "%s %s " % (self.names[0], v)
  512. class _Switch(_AbstractParameter):
  513. """Represent an optional argument switch for a program.
  514. This holds UNIXish options like -kimura in clustalw which don't
  515. take a value, they are either included in the command string
  516. or omitted.
  517. o names -- a list of string names (typically two entries) by which
  518. the parameter can be set via the legacy set_parameter method
  519. (eg ["-a", "--append", "append"]). The first name in list is used
  520. when building the command line. The last name in the list is a
  521. "human readable" name describing the option in one word. This
  522. must be a valid Python identifer as it is used as the property
  523. name and as a keyword argument, and should therefore follow PEP8
  524. naming.
  525. o description -- a description of the option. This is used as
  526. the property docstring.
  527. o is_set -- if the parameter has been set
  528. NOTE - There is no value attribute, see is_set instead,
  529. """
  530. def __init__(self, names, description):
  531. self.names = names
  532. self.description = description
  533. self.is_set = False
  534. self.is_required = False
  535. def __str__(self):
  536. """Return the value of this option for the commandline.
  537. Includes a trailing space.
  538. """
  539. assert not hasattr(self, "value")
  540. if self.is_set:
  541. return "%s " % self.names[0]
  542. else:
  543. return ""
  544. class _Argument(_AbstractParameter):
  545. """Represent an argument on a commandline.
  546. The names argument should be a list containing one string.
  547. This must be a valid Python identifer as it is used as the
  548. property name and as a keyword argument, and should therefore
  549. follow PEP8 naming.
  550. """
  551. def __init__(self, names, description, filename=False,
  552. checker_function=None, is_required=False):
  553. # if len(names) != 1:
  554. # raise ValueError("The names argument to _Argument should be a "
  555. # "single entry list with a PEP8 property name.")
  556. self.names = names
  557. assert isinstance(description, basestring), \
  558. "%r for %s" % (description, names[-1])
  559. self.is_filename = filename
  560. self.checker_function = checker_function
  561. self.description = description
  562. self.is_required = is_required
  563. self.is_set = False
  564. self.value = None
  565. def __str__(self):
  566. if self.value is None:
  567. return " "
  568. elif self.is_filename:
  569. return "%s " % _escape_filename(self.value)
  570. else:
  571. return "%s " % self.value
  572. class _ArgumentList(_Argument):
  573. """Represent a variable list of arguments on a command line, e.g. multiple filenames."""
  574. # TODO - Option to require at least one value? e.g. min/max count?
  575. def __str__(self):
  576. assert isinstance(self.value, list), \
  577. "Arguments should be a list"
  578. assert self.value, "Requires at least one filename"
  579. # A trailing space is required so that parameters following the last filename
  580. # do not appear merged.
  581. # e.g.: samtools cat in1.bam in2.bam-o out.sam [without trailing space][Incorrect]
  582. # samtools cat in1.bam in2.bam -o out.sam [with trailing space][Correct]
  583. if self.is_filename:
  584. return " ".join(_escape_filename(v) for v in self.value) + " "
  585. else:
  586. return " ".join(self.value) + " "
  587. class _StaticArgument(_AbstractParameter):
  588. """Represent a static (read only) argument on a commandline.
  589. This is not intended to be exposed as a named argument or
  590. property of a command line wrapper object.
  591. """
  592. def __init__(self, value):
  593. self.names = []
  594. self.is_required = False
  595. self.is_set = True
  596. self.value = value
  597. def __str__(self):
  598. return "%s " % self.value
  599. def _escape_filename(filename):
  600. """Escape filenames with spaces by adding quotes (PRIVATE).
  601. Note this will not add quotes if they are already included:
  602. >>> print((_escape_filename('example with spaces')))
  603. "example with spaces"
  604. >>> print((_escape_filename('"example with spaces"')))
  605. "example with spaces"
  606. """
  607. # Is adding the following helpful
  608. # if os.path.isfile(filename):
  609. # # On Windows, if the file exists, we can ask for
  610. # # its alternative short name (DOS style 8.3 format)
  611. # # which has no spaces in it. Note that this name
  612. # # is not portable between machines, or even folder!
  613. # try:
  614. # import win32api
  615. # short = win32api.GetShortPathName(filename)
  616. # assert os.path.isfile(short)
  617. # return short
  618. # except ImportError:
  619. # pass
  620. if " " not in filename:
  621. return filename
  622. # We'll just quote it - works on Windows, Mac OS X etc
  623. if filename.startswith('"') and filename.endswith('"'):
  624. # Its already quoted
  625. return filename
  626. else:
  627. return '"%s"' % filename
  628. def _test():
  629. """Run the Bio.Application module's doctests."""
  630. import doctest
  631. doctest.testmod(verbose=1)
  632. if __name__ == "__main__":
  633. # Run the doctests
  634. _test()