module.py 23 KB

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