module.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. # -*- coding: utf-8 -*-
  2. from __future__ import (nested_scopes, generators, division, absolute_import,
  3. with_statement, print_function, unicode_literals)
  4. import sys
  5. from multiprocessing import cpu_count
  6. from functools import wraps
  7. if sys.version_info[0] == 2:
  8. from itertools import izip_longest as zip_longest
  9. else:
  10. from itertools import zip_longest
  11. from xml.etree.ElementTree import fromstring
  12. import time
  13. from grass.exceptions import CalledModuleError
  14. from grass.script.core import Popen, PIPE
  15. from grass.pygrass.errors import GrassError, ParameterError
  16. from grass.pygrass.utils import docstring_property
  17. from grass.pygrass.modules.interface.parameter import Parameter
  18. from grass.pygrass.modules.interface.flag import Flag
  19. from grass.pygrass.modules.interface.typedict import TypeDict
  20. from grass.pygrass.modules.interface.read import GETFROMTAG, DOC
  21. from grass.pygrass.messages import get_msgr
  22. def mdebug(level, msg='', extra=None):
  23. """Debug decorators for class methods.
  24. :param level: the debug level
  25. :type level: int
  26. :param msg: Debug message
  27. :type msg: str
  28. :param extra: Function that return a string
  29. :type msg: func
  30. """
  31. msgr = get_msgr()
  32. def decorator(method):
  33. @wraps(method)
  34. def wrapper(self, *args, **kargs):
  35. sargs = ', ' + ' , '.join([repr(a) for a in args]) if args else ''
  36. skargs = (' , '.join(['%s=%r' % (k, v) for k, v in kargs.items()])
  37. if kargs else '')
  38. opts = "%s%s%s" % (sargs, ',' if sargs and skargs else '', skargs)
  39. dmsg = "%s.%s(self%s): %s %s" % (self.__class__.__name__,
  40. method.__name__,
  41. opts, msg,
  42. extra(self, *args, **kargs)
  43. if extra else '')
  44. msgr.debug(level, dmsg)
  45. return method(self, *args, **kargs)
  46. return wrapper
  47. return decorator
  48. def _get_bash(self, *args, **kargs):
  49. return self.get_bash()
  50. class ParallelModuleQueue(object):
  51. """This class is designed to run an arbitrary number of pygrass Module
  52. processes in parallel.
  53. Objects of type grass.pygrass.modules.Module can be put into the
  54. queue using put() method. When the queue is full with the maximum
  55. number of parallel processes it will wait for all processes to finish,
  56. sets the stdout and stderr of the Module object and removes it
  57. from the queue when its finished.
  58. To finish the queue before the maximum number of parallel
  59. processes was reached call wait() .
  60. This class will raise a GrassError in case a Module process exits
  61. with a return code other than 0.
  62. Usage:
  63. Check with a queue size of 3 and 5 processes
  64. >>> import copy
  65. >>> from grass.pygrass.modules import Module, ParallelModuleQueue
  66. >>> mapcalc_list = []
  67. Setting run_ to False is important, otherwise a parallel processing is not possible
  68. >>> mapcalc = Module("r.mapcalc", overwrite=True, run_=False)
  69. >>> queue = ParallelModuleQueue(nprocs=3)
  70. >>> for i in xrange(5):
  71. ... new_mapcalc = copy.deepcopy(mapcalc)
  72. ... mapcalc_list.append(new_mapcalc)
  73. ... m = new_mapcalc(expression="test_pygrass_%i = %i"%(i, i))
  74. ... queue.put(m)
  75. >>> queue.wait()
  76. >>> queue.get_num_run_procs()
  77. 0
  78. >>> queue.get_max_num_procs()
  79. 3
  80. >>> for mapcalc in mapcalc_list:
  81. ... print(mapcalc.popen.returncode)
  82. 0
  83. 0
  84. 0
  85. 0
  86. 0
  87. Check with a queue size of 8 and 5 processes
  88. >>> queue = ParallelModuleQueue(nprocs=8)
  89. >>> mapcalc_list = []
  90. >>> for i in xrange(5):
  91. ... new_mapcalc = copy.deepcopy(mapcalc)
  92. ... mapcalc_list.append(new_mapcalc)
  93. ... m = new_mapcalc(expression="test_pygrass_%i = %i"%(i, i))
  94. ... queue.put(m)
  95. >>> queue.wait()
  96. >>> queue.get_num_run_procs()
  97. 0
  98. >>> queue.get_max_num_procs()
  99. 8
  100. >>> for mapcalc in mapcalc_list:
  101. ... print(mapcalc.popen.returncode)
  102. 0
  103. 0
  104. 0
  105. 0
  106. 0
  107. Check with a queue size of 8 and 4 processes
  108. >>> queue = ParallelModuleQueue(nprocs=8)
  109. >>> mapcalc_list = []
  110. >>> new_mapcalc = copy.deepcopy(mapcalc)
  111. >>> mapcalc_list.append(new_mapcalc)
  112. >>> m = new_mapcalc(expression="test_pygrass_1 =1")
  113. >>> queue.put(m)
  114. >>> queue.get_num_run_procs()
  115. 1
  116. >>> new_mapcalc = copy.deepcopy(mapcalc)
  117. >>> mapcalc_list.append(new_mapcalc)
  118. >>> m = new_mapcalc(expression="test_pygrass_2 =2")
  119. >>> queue.put(m)
  120. >>> queue.get_num_run_procs()
  121. 2
  122. >>> new_mapcalc = copy.deepcopy(mapcalc)
  123. >>> mapcalc_list.append(new_mapcalc)
  124. >>> m = new_mapcalc(expression="test_pygrass_3 =3")
  125. >>> queue.put(m)
  126. >>> queue.get_num_run_procs()
  127. 3
  128. >>> new_mapcalc = copy.deepcopy(mapcalc)
  129. >>> mapcalc_list.append(new_mapcalc)
  130. >>> m = new_mapcalc(expression="test_pygrass_4 =4")
  131. >>> queue.put(m)
  132. >>> queue.get_num_run_procs()
  133. 4
  134. >>> queue.wait()
  135. >>> queue.get_num_run_procs()
  136. 0
  137. >>> queue.get_max_num_procs()
  138. 8
  139. >>> for mapcalc in mapcalc_list:
  140. ... print(mapcalc.popen.returncode)
  141. 0
  142. 0
  143. 0
  144. 0
  145. Check with a queue size of 3 and 4 processes
  146. >>> queue = ParallelModuleQueue(nprocs=3)
  147. >>> mapcalc_list = []
  148. >>> new_mapcalc = copy.deepcopy(mapcalc)
  149. >>> mapcalc_list.append(new_mapcalc)
  150. >>> m = new_mapcalc(expression="test_pygrass_1 =1")
  151. >>> queue.put(m)
  152. >>> queue.get_num_run_procs()
  153. 1
  154. >>> new_mapcalc = copy.deepcopy(mapcalc)
  155. >>> mapcalc_list.append(new_mapcalc)
  156. >>> m = new_mapcalc(expression="test_pygrass_2 =2")
  157. >>> queue.put(m)
  158. >>> queue.get_num_run_procs()
  159. 2
  160. >>> new_mapcalc = copy.deepcopy(mapcalc)
  161. >>> mapcalc_list.append(new_mapcalc)
  162. >>> m = new_mapcalc(expression="test_pygrass_3 =3")
  163. >>> queue.put(m) # Now it will wait until all procs finish and set the counter back to 0
  164. >>> queue.get_num_run_procs()
  165. 0
  166. >>> new_mapcalc = copy.deepcopy(mapcalc)
  167. >>> mapcalc_list.append(new_mapcalc)
  168. >>> m = new_mapcalc(expression="test_pygrass_%i = %i"%(i, i))
  169. >>> queue.put(m)
  170. >>> queue.get_num_run_procs()
  171. 1
  172. >>> queue.wait()
  173. >>> queue.get_num_run_procs()
  174. 0
  175. >>> queue.get_max_num_procs()
  176. 3
  177. >>> for mapcalc in mapcalc_list:
  178. ... print(mapcalc.popen.returncode)
  179. 0
  180. 0
  181. 0
  182. 0
  183. """
  184. def __init__(self, nprocs=1):
  185. """Constructor
  186. :param nprocs: The maximum number of Module processes that
  187. can be run in parallel, defualt is 1, if None
  188. then use all the available CPUs.
  189. :type nprocs: int
  190. """
  191. nprocs = int(nprocs) if nprocs else cpu_count()
  192. self._num_procs = nprocs
  193. self._list = nprocs * [None]
  194. self._proc_count = 0
  195. def put(self, module):
  196. """Put the next Module object in the queue
  197. To run the Module objects in parallel the run\_ and finish\_ options
  198. of the Module must be set to False.
  199. :param module: a preconfigured Module object with run\_ and finish\_
  200. set to False
  201. :type module: Module object
  202. """
  203. self._list[self._proc_count] = module
  204. # Force that finish is False, otherwise the execution
  205. # will not be parallel
  206. self._list[self._proc_count].finish_ = False
  207. self._list[self._proc_count].run()
  208. self._proc_count += 1
  209. if self._proc_count == self._num_procs:
  210. self.wait()
  211. def get(self, num):
  212. """Get a Module object from the queue
  213. :param num: the number of the object in queue
  214. :type num: int
  215. :returns: the Module object or None if num is not in the queue
  216. """
  217. if num < self._num_procs:
  218. return self._list[num]
  219. return None
  220. def get_num_run_procs(self):
  221. """Get the number of Module processes that are in the queue running
  222. or finished
  223. :returns: the number fo Module processes running/finished in the queue
  224. """
  225. return self._proc_count
  226. def get_max_num_procs(self):
  227. """Return the maximum number of parallel Module processes
  228. :returns: the maximum number of parallel Module processes
  229. """
  230. return self._num_procs
  231. def set_max_num_procs(self, nprocs):
  232. """Set the maximum number of Module processes that should run
  233. in parallel
  234. :param nprocs: The maximum number of Module processes that can be
  235. run in parallel
  236. :type nprocs: int
  237. """
  238. self._num_procs = int(nprocs)
  239. self.wait()
  240. def wait(self):
  241. """Wait for all Module processes that are in the list to finish
  242. and set the modules stdout and stderr output options
  243. """
  244. for proc in self._list:
  245. if proc:
  246. stdout, stderr = proc.popen.communicate(input=proc.stdin)
  247. proc.outputs['stdout'].value = stdout if stdout else ''
  248. proc.outputs['stderr'].value = stderr if stderr else ''
  249. if proc.popen.returncode != 0:
  250. GrassError(("Error running module %s") % (proc.name))
  251. self._list = self._num_procs * [None]
  252. self._proc_count = 0
  253. class Module(object):
  254. """This class is design to wrap/run/interact with the GRASS modules.
  255. The class during the init phase read the XML description generate using
  256. the ``--interface-description`` in order to understand which parameters
  257. are required which optionals. ::
  258. >>> from grass.pygrass.modules import Module
  259. >>> from subprocess import PIPE
  260. >>> import copy
  261. >>> region = Module("g.region")
  262. >>> region.flags.p = True # set flags
  263. >>> region.flags.u = True
  264. >>> region.flags["3"].value = True # set numeric flags
  265. >>> region.get_bash()
  266. u'g.region -p -3 -u'
  267. >>> new_region = copy.deepcopy(region)
  268. >>> new_region.inputs.res = "10"
  269. >>> new_region.get_bash()
  270. u'g.region res=10 -p -3 -u'
  271. >>> neighbors = Module("r.neighbors")
  272. >>> neighbors.inputs.input = "mapA"
  273. >>> neighbors.outputs.output = "mapB"
  274. >>> neighbors.inputs.size = 5
  275. >>> neighbors.inputs.quantile = 0.5
  276. >>> neighbors.get_bash()
  277. u'r.neighbors input=mapA method=average size=5 quantile=0.5 output=mapB'
  278. >>> new_neighbors1 = copy.deepcopy(neighbors)
  279. >>> new_neighbors1.inputs.input = "mapD"
  280. >>> new_neighbors1.inputs.size = 3
  281. >>> new_neighbors1.inputs.quantile = 0.5
  282. >>> new_neighbors1.get_bash()
  283. u'r.neighbors input=mapD method=average size=3 quantile=0.5 output=mapB'
  284. >>> new_neighbors2 = copy.deepcopy(neighbors)
  285. >>> new_neighbors2(input="mapD", size=3, run_=False)
  286. Module('r.neighbors')
  287. >>> new_neighbors2.get_bash()
  288. u'r.neighbors input=mapD method=average size=3 quantile=0.5 output=mapB'
  289. >>> neighbors = Module("r.neighbors")
  290. >>> neighbors.get_bash()
  291. u'r.neighbors method=average size=3'
  292. >>> new_neighbors3 = copy.deepcopy(neighbors)
  293. >>> new_neighbors3(input="mapA", size=3, output="mapB", run_=False)
  294. Module('r.neighbors')
  295. >>> new_neighbors3.get_bash()
  296. u'r.neighbors input=mapA method=average size=3 output=mapB'
  297. >>> mapcalc = Module("r.mapcalc", expression="test_a = 1",
  298. ... overwrite=True, run_=False)
  299. >>> mapcalc.run()
  300. Module('r.mapcalc')
  301. >>> mapcalc.popen.returncode
  302. 0
  303. >>> colors = Module("r.colors", map="test_a", rules="-",
  304. ... run_=False, stdout_=PIPE,
  305. ... stderr_=PIPE, stdin_="1 red")
  306. >>> colors.run()
  307. Module('r.colors')
  308. >>> colors.popen.returncode
  309. 0
  310. >>> colors.inputs["stdin"].value
  311. u'1 red'
  312. >>> colors.outputs["stdout"].value
  313. u''
  314. >>> colors.outputs["stderr"].value.strip()
  315. "Color table for raster map <test_a> set to 'rules'"
  316. >>> colors = Module("r.colors", map="test_a", rules="-",
  317. ... run_=False, finish_=False, stdin_=PIPE)
  318. >>> colors.run()
  319. Module('r.colors')
  320. >>> stdout, stderr = colors.popen.communicate(input="1 red")
  321. >>> colors.popen.returncode
  322. 0
  323. >>> stdout
  324. >>> stderr
  325. >>> colors = Module("r.colors", map="test_a", rules="-",
  326. ... run_=False, finish_=False,
  327. ... stdin_=PIPE, stderr_=PIPE)
  328. >>> colors.run()
  329. Module('r.colors')
  330. >>> stdout, stderr = colors.popen.communicate(input="1 red")
  331. >>> colors.popen.returncode
  332. 0
  333. >>> stdout
  334. >>> stderr.strip()
  335. "Color table for raster map <test_a> set to 'rules'"
  336. Run a second time
  337. >>> colors.run()
  338. Module('r.colors')
  339. >>> stdout, stderr = colors.popen.communicate(input="1 blue")
  340. >>> colors.popen.returncode
  341. 0
  342. >>> stdout
  343. >>> stderr.strip()
  344. "Color table for raster map <test_a> set to 'rules'"
  345. Multiple run test
  346. >>> colors = Module("r.colors", map="test_a",
  347. ... color="ryb", run_=False)
  348. >>> colors.run()
  349. Module('r.colors')
  350. >>> colors(color="gyr")
  351. Module('r.colors')
  352. >>> colors.run()
  353. Module('r.colors')
  354. >>> colors(color="ryg")
  355. Module('r.colors')
  356. >>> colors(stderr_=PIPE)
  357. Module('r.colors')
  358. >>> colors.run()
  359. Module('r.colors')
  360. >>> print(colors.outputs["stderr"].value.strip())
  361. Color table for raster map <test_a> set to 'ryg'
  362. >>> colors(color="byg")
  363. Module('r.colors')
  364. >>> colors(stdout_=PIPE)
  365. Module('r.colors')
  366. >>> colors.run()
  367. Module('r.colors')
  368. >>> print(colors.outputs["stderr"].value.strip())
  369. Color table for raster map <test_a> set to 'byg'
  370. Often in the Module class you can find ``*args`` and ``kwargs`` annotation
  371. in methods, like in the __call__ method.
  372. Python allow developers to not specify all the arguments and
  373. keyword arguments of a method or function. ::
  374. def f(*args):
  375. for arg in args:
  376. print arg
  377. therefore if we call the function like:
  378. >>> f('grass', 'gis', 'modules') # doctest: +SKIP
  379. grass
  380. gis
  381. modules
  382. or we can define a new list:
  383. >>> words = ['grass', 'gis', 'modules'] # doctest: +SKIP
  384. >>> f(*words) # doctest: +SKIP
  385. grass
  386. gis
  387. modules
  388. we can do the same with keyword arguments, rewrite the above function: ::
  389. def f(*args, **kargs):
  390. for arg in args:
  391. print arg
  392. for key, value in kargs.items():
  393. print "%s = %r" % (key, value)
  394. now we can use the new function, with:
  395. >>> f('grass', 'gis', 'modules', os = 'linux', language = 'python')
  396. ... # doctest: +SKIP
  397. grass
  398. gis
  399. modules
  400. os = 'linux'
  401. language = 'python'
  402. or, as before we can, define a dictionary and give the dictionary to
  403. the function, like:
  404. >>> keywords = {'os' : 'linux', 'language' : 'python'} # doctest: +SKIP
  405. >>> f(*words, **keywords) # doctest: +SKIP
  406. grass
  407. gis
  408. modules
  409. os = 'linux'
  410. language = 'python'
  411. In the Module class we heavily use this language feature to pass arguments
  412. and keyword arguments to the grass module.
  413. """
  414. def __init__(self, cmd, *args, **kargs):
  415. if isinstance(cmd, unicode):
  416. self.name = str(cmd)
  417. elif isinstance(cmd, str):
  418. self.name = cmd
  419. else:
  420. raise GrassError("Problem initializing the module {s}".format(s=cmd))
  421. try:
  422. # call the command with --interface-description
  423. get_cmd_xml = Popen([cmd, "--interface-description"], stdout=PIPE)
  424. except OSError as e:
  425. print("OSError error({0}): {1}".format(e.errno, e.strerror))
  426. str_err = "Error running: `%s --interface-description`."
  427. raise GrassError(str_err % self.name)
  428. # get the xml of the module
  429. self.xml = get_cmd_xml.communicate()[0]
  430. # transform and parse the xml into an Element class:
  431. # http://docs.python.org/library/xml.etree.elementtree.html
  432. tree = fromstring(self.xml)
  433. for e in tree:
  434. if e.tag not in ('parameter', 'flag'):
  435. self.__setattr__(e.tag, GETFROMTAG[e.tag](e))
  436. #
  437. # extract parameters from the xml
  438. #
  439. self.params_list = [Parameter(p) for p in tree.findall("parameter")]
  440. self.inputs = TypeDict(Parameter)
  441. self.outputs = TypeDict(Parameter)
  442. self.required = []
  443. # Insert parameters into input/output and required
  444. for par in self.params_list:
  445. if par.input:
  446. self.inputs[par.name] = par
  447. else:
  448. self.outputs[par.name] = par
  449. if par.required:
  450. self.required.append(par.name)
  451. #
  452. # extract flags from the xml
  453. #
  454. flags_list = [Flag(f) for f in tree.findall("flag")]
  455. self.flags = TypeDict(Flag)
  456. for flag in flags_list:
  457. self.flags[flag.name] = flag
  458. #
  459. # Add new attributes to the class
  460. #
  461. self.run_ = True
  462. self.finish_ = True
  463. self.env_ = None
  464. self.stdin_ = None
  465. self.stdin = None
  466. self.stdout_ = None
  467. self.stderr_ = None
  468. diz = {'name': 'stdin', 'required': False,
  469. 'multiple': False, 'type': 'all',
  470. 'value': None}
  471. self.inputs['stdin'] = Parameter(diz=diz)
  472. diz['name'] = 'stdout'
  473. self.outputs['stdout'] = Parameter(diz=diz)
  474. diz['name'] = 'stderr'
  475. self.outputs['stderr'] = Parameter(diz=diz)
  476. self.popen = None
  477. self.time = None
  478. if args or kargs:
  479. self.__call__(*args, **kargs)
  480. self.__call__.__func__.__doc__ = self.__doc__
  481. def __call__(self, *args, **kargs):
  482. """Set module paramters to the class and, if run_ is True execute the
  483. module, therefore valid parameters are all the module parameters
  484. plus some extra parameters that are: run_, stdin_, stdout_, stderr_,
  485. env_ and finish_.
  486. """
  487. if not args and not kargs:
  488. self.run()
  489. return self
  490. #
  491. # check for extra kargs, set attribute and remove from dictionary
  492. #
  493. if 'flags' in kargs:
  494. for flg in kargs['flags']:
  495. self.flags[flg].value = True
  496. del(kargs['flags'])
  497. # set attributs
  498. for key in ('run_', 'env_', 'finish_', 'stdout_', 'stderr_'):
  499. if key in kargs:
  500. setattr(self, key, kargs.pop(key))
  501. # set inputs
  502. for key in ('stdin_', ):
  503. if key in kargs:
  504. self.inputs[key[:-1]].value = kargs.pop(key)
  505. #
  506. # check args
  507. #
  508. for param, arg in zip(self.params_list, args):
  509. param.value = arg
  510. for key, val in kargs.items():
  511. if key in self.inputs:
  512. self.inputs[key].value = val
  513. elif key in self.outputs:
  514. self.outputs[key].value = val
  515. elif key in self.flags:
  516. # we need to add this, because some parameters (overwrite,
  517. # verbose and quiet) work like parameters
  518. self.flags[key].value = val
  519. else:
  520. raise ParameterError('%s is not a valid parameter.' % key)
  521. #
  522. # check if execute
  523. #
  524. if self.run_:
  525. #
  526. # check reqire parameters
  527. #
  528. for k in self.required:
  529. if ((k in self.inputs and self.inputs[k].value is None) or
  530. (k in self.outputs and self.outputs[k].value is None)):
  531. msg = "Required parameter <%s> not set."
  532. raise ParameterError(msg % k)
  533. return self.run()
  534. return self
  535. def get_bash(self):
  536. """Return a BASH rapresentation of the Module."""
  537. return ' '.join(self.make_cmd())
  538. def get_python(self):
  539. """Return a Python rapresentation of the Module."""
  540. prefix = self.name.split('.')[0]
  541. name = '_'.join(self.name.split('.')[1:])
  542. params = ', '.join([par.get_python() for par in self.params_list
  543. if par.get_python() != ''])
  544. flags = ''.join([flg.get_python()
  545. for flg in self.flags.values()
  546. if not flg.special and flg.get_python() != ''])
  547. special = ', '.join([flg.get_python()
  548. for flg in self.flags.values()
  549. if flg.special and flg.get_python() != ''])
  550. # pre name par flg special
  551. if flags and special:
  552. return "%s.%s(%s, flags=%r, %s)" % (prefix, name, params,
  553. flags, special)
  554. elif flags:
  555. return "%s.%s(%s, flags=%r)" % (prefix, name, params, flags)
  556. elif special:
  557. return "%s.%s(%s, %s)" % (prefix, name, params, special)
  558. else:
  559. return "%s.%s(%s)" % (prefix, name, params)
  560. def __str__(self):
  561. """Return the command string that can be executed in a shell"""
  562. return ' '.join(self.make_cmd())
  563. def __repr__(self):
  564. return "Module(%r)" % self.name
  565. @docstring_property(__doc__)
  566. def __doc__(self):
  567. """{cmd_name}({cmd_params})
  568. """
  569. head = DOC['head'].format(cmd_name=self.name,
  570. cmd_params=('\n' + # go to a new line
  571. # give space under the function name
  572. (' ' * (len(self.name) + 1))).join([', '.join(
  573. # transform each parameter in string
  574. [str(param) for param in line if param is not None])
  575. # make a list of parameters with only 3 param per line
  576. for line in zip_longest(*[iter(self.params_list)] * 3)]),)
  577. params = '\n'.join([par.__doc__ for par in self.params_list])
  578. flags = self.flags.__doc__
  579. return '\n'.join([head, params, DOC['flag_head'], flags, DOC['foot']])
  580. def get_dict(self):
  581. """Return a dictionary that includes the name, all valid
  582. inputs, outputs and flags
  583. """
  584. dic = {}
  585. dic['name'] = self.name
  586. dic['inputs'] = [(k, v.value) for k, v in self.inputs.items()
  587. if v.value]
  588. dic['outputs'] = [(k, v.value) for k, v in self.outputs.items()
  589. if v.value]
  590. dic['flags'] = [flg for flg in self.flags if self.flags[flg].value]
  591. return dic
  592. def make_cmd(self):
  593. """Create the command string that can be executed in a shell
  594. :returns: the command string
  595. """
  596. skip = ['stdin', 'stdout', 'stderr']
  597. args = [self.name, ]
  598. for key in self.inputs:
  599. if key not in skip and self.inputs[key].value:
  600. args.append(self.inputs[key].get_bash())
  601. for key in self.outputs:
  602. if key not in skip and self.outputs[key].value:
  603. args.append(self.outputs[key].get_bash())
  604. for flg in self.flags:
  605. if self.flags[flg].value:
  606. args.append(str(self.flags[flg]))
  607. return args
  608. @mdebug(1, extra=_get_bash)
  609. def run(self):
  610. """Run the module
  611. :param node:
  612. :type node:
  613. This function will wait for the process to terminate in case
  614. finish_==True and sets up stdout and stderr. If finish_==False this
  615. function will return after starting the process. Use
  616. self.popen.communicate() of self.popen.wait() to wait for the process
  617. termination. The handling of stdout and stderr must then be done
  618. outside of this function.
  619. """
  620. if self.inputs['stdin'].value:
  621. self.stdin = self.inputs['stdin'].value
  622. self.stdin_ = PIPE
  623. cmd = self.make_cmd()
  624. start = time.time()
  625. self.popen = Popen(cmd,
  626. stdin=self.stdin_,
  627. stdout=self.stdout_,
  628. stderr=self.stderr_,
  629. env=self.env_)
  630. if self.finish_:
  631. stdout, stderr = self.popen.communicate(input=self.stdin)
  632. self.outputs['stdout'].value = stdout if stdout else ''
  633. self.outputs['stderr'].value = stderr if stderr else ''
  634. self.time = time.time() - start
  635. if self.popen.poll():
  636. raise CalledModuleError(returncode=self.popen.returncode,
  637. code=self.get_bash(),
  638. module=self.name, errors=stderr)
  639. return self
  640. ###############################################################################
  641. if __name__ == "__main__":
  642. import doctest
  643. doctest.testmod()