module.py 23 KB

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