module.py 24 KB

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