PageRenderTime 44ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/Bio/Application/__init__.py

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