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. 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.run()
  322. Module('r.colors')
  323. >>> colors(color="gyr")
  324. Module('r.colors')
  325. >>> colors.run()
  326. Module('r.colors')
  327. >>> colors(color="ryg")
  328. Module('r.colors')
  329. >>> colors(stderr_=PIPE)
  330. Module('r.colors')
  331. >>> colors.run()
  332. Module('r.colors')
  333. >>> print(colors.outputs["stderr"].value.strip())
  334. Color table for raster map <test_a> set to 'ryg'
  335. >>> colors(color="byg")
  336. Module('r.colors')
  337. >>> colors(stdout_=PIPE)
  338. Module('r.colors')
  339. >>> colors.run()
  340. Module('r.colors')
  341. >>> print(colors.outputs["stderr"].value.strip())
  342. Color table for raster map <test_a> set to 'byg'
  343. Often in the Module class you can find ``*args`` and ``kwargs`` annotation
  344. in methods, like in the __call__ method.
  345. Python allow developers to not specify all the arguments and
  346. keyword arguments of a method or function. ::
  347. def f(*args):
  348. for arg in args:
  349. print arg
  350. therefore if we call the function like:
  351. >>> f('grass', 'gis', 'modules') # doctest: +SKIP
  352. grass
  353. gis
  354. modules
  355. or we can define a new list:
  356. >>> words = ['grass', 'gis', 'modules'] # doctest: +SKIP
  357. >>> f(*words) # doctest: +SKIP
  358. grass
  359. gis
  360. modules
  361. we can do the same with keyword arguments, rewrite the above function: ::
  362. def f(*args, **kargs):
  363. for arg in args:
  364. print arg
  365. for key, value in kargs.items():
  366. print "%s = %r" % (key, value)
  367. now we can use the new function, with:
  368. >>> f('grass', 'gis', 'modules', os = 'linux', language = 'python')
  369. ... # doctest: +SKIP
  370. grass
  371. gis
  372. modules
  373. os = 'linux'
  374. language = 'python'
  375. or, as before we can, define a dictionary and give the dictionary to
  376. the function, like:
  377. >>> keywords = {'os' : 'linux', 'language' : 'python'} # doctest: +SKIP
  378. >>> f(*words, **keywords) # doctest: +SKIP
  379. grass
  380. gis
  381. modules
  382. os = 'linux'
  383. language = 'python'
  384. In the Module class we heavily use this language feature to pass arguments
  385. and keyword arguments to the grass module.
  386. """
  387. def __init__(self, cmd, *args, **kargs):
  388. if isinstance(cmd, unicode):
  389. self.name = str(cmd)
  390. elif isinstance(cmd, str):
  391. self.name = cmd
  392. else:
  393. raise GrassError("Problem initializing the module {s}".format(s=cmd))
  394. try:
  395. # call the command with --interface-description
  396. get_cmd_xml = Popen([cmd, "--interface-description"], stdout=PIPE)
  397. except OSError as e:
  398. print("OSError error({0}): {1}".format(e.errno, e.strerror))
  399. str_err = "Error running: `%s --interface-description`."
  400. raise GrassError(str_err % self.name)
  401. # get the xml of the module
  402. self.xml = get_cmd_xml.communicate()[0]
  403. # transform and parse the xml into an Element class:
  404. # http://docs.python.org/library/xml.etree.elementtree.html
  405. tree = fromstring(self.xml)
  406. for e in tree:
  407. if e.tag not in ('parameter', 'flag'):
  408. self.__setattr__(e.tag, GETFROMTAG[e.tag](e))
  409. #
  410. # extract parameters from the xml
  411. #
  412. self.params_list = [Parameter(p) for p in tree.findall("parameter")]
  413. self.inputs = TypeDict(Parameter)
  414. self.outputs = TypeDict(Parameter)
  415. self.required = []
  416. # Insert parameters into input/output and required
  417. for par in self.params_list:
  418. if par.input:
  419. self.inputs[par.name] = par
  420. else:
  421. self.outputs[par.name] = par
  422. if par.required:
  423. self.required.append(par.name)
  424. #
  425. # extract flags from the xml
  426. #
  427. flags_list = [Flag(f) for f in tree.findall("flag")]
  428. self.flags = TypeDict(Flag)
  429. for flag in flags_list:
  430. self.flags[flag.name] = flag
  431. #
  432. # Add new attributes to the class
  433. #
  434. self.run_ = True
  435. self.finish_ = True
  436. self.env_ = None
  437. self.stdin_ = None
  438. self.stdin = None
  439. self.stdout_ = None
  440. self.stderr_ = None
  441. diz = {'name': 'stdin', 'required': False,
  442. 'multiple': False, 'type': 'all',
  443. 'value': None}
  444. self.inputs['stdin'] = Parameter(diz=diz)
  445. diz['name'] = 'stdout'
  446. self.outputs['stdout'] = Parameter(diz=diz)
  447. diz['name'] = 'stderr'
  448. self.outputs['stderr'] = Parameter(diz=diz)
  449. self.popen = None
  450. self.time = None
  451. if args or kargs:
  452. self.__call__(*args, **kargs)
  453. self.__call__.__func__.__doc__ = self.__doc__
  454. def __call__(self, *args, **kargs):
  455. """Set module parameters to the class and, if run_ is True execute the
  456. module, therefore valid parameters are all the module parameters
  457. plus some extra parameters that are: run_, stdin_, stdout_, stderr_,
  458. env_ and finish_.
  459. """
  460. if not args and not kargs:
  461. self.run()
  462. return self
  463. #
  464. # check for extra kargs, set attribute and remove from dictionary
  465. #
  466. if 'flags' in kargs:
  467. for flg in kargs['flags']:
  468. self.flags[flg].value = True
  469. del(kargs['flags'])
  470. # set attributs
  471. for key in ('run_', 'env_', 'finish_', 'stdout_', 'stderr_'):
  472. if key in kargs:
  473. setattr(self, key, kargs.pop(key))
  474. # set inputs
  475. for key in ('stdin_', ):
  476. if key in kargs:
  477. self.inputs[key[:-1]].value = kargs.pop(key)
  478. #
  479. # check args
  480. #
  481. for param, arg in zip(self.params_list, args):
  482. param.value = arg
  483. for key, val in kargs.items():
  484. if key in self.inputs:
  485. self.inputs[key].value = val
  486. elif key in self.outputs:
  487. self.outputs[key].value = val
  488. elif key in self.flags:
  489. # we need to add this, because some parameters (overwrite,
  490. # verbose and quiet) work like parameters
  491. self.flags[key].value = val
  492. else:
  493. raise ParameterError('%s is not a valid parameter.' % key)
  494. #
  495. # check if execute
  496. #
  497. if self.run_:
  498. #
  499. # check reqire parameters
  500. #
  501. for k in self.required:
  502. if ((k in self.inputs and self.inputs[k].value is None) or
  503. (k in self.outputs and self.outputs[k].value is None)):
  504. msg = "Required parameter <%s> not set."
  505. raise ParameterError(msg % k)
  506. return self.run()
  507. return self
  508. def get_bash(self):
  509. """Return a BASH rapresentation of the Module."""
  510. return ' '.join(self.make_cmd())
  511. def get_python(self):
  512. """Return a Python rapresentation 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 get_dict(self):
  554. """Return a dictionary that includes the name, all valid
  555. inputs, outputs and flags
  556. """
  557. dic = {}
  558. dic['name'] = self.name
  559. dic['inputs'] = [(k, v.value) for k, v in self.inputs.items()
  560. if v.value]
  561. dic['outputs'] = [(k, v.value) for k, v in self.outputs.items()
  562. if v.value]
  563. dic['flags'] = [flg for flg in self.flags if self.flags[flg].value]
  564. return dic
  565. def make_cmd(self):
  566. """Create the command string that can be executed in a shell
  567. :returns: the command string
  568. """
  569. skip = ['stdin', 'stdout', 'stderr']
  570. args = [self.name, ]
  571. for key in self.inputs:
  572. if key not in skip and self.inputs[key].value:
  573. args.append(self.inputs[key].get_bash())
  574. for key in self.outputs:
  575. if key not in skip and self.outputs[key].value:
  576. args.append(self.outputs[key].get_bash())
  577. for flg in self.flags:
  578. if self.flags[flg].value:
  579. args.append(str(self.flags[flg]))
  580. return args
  581. def run(self):
  582. """Run the module
  583. :param node:
  584. :type node:
  585. This function will wait for the process to terminate in case
  586. finish_==True and sets up stdout and stderr. If finish_==False this
  587. function will return after starting the process. Use
  588. self.popen.communicate() of self.popen.wait() to wait for the process
  589. termination. The handling of stdout and stderr must then be done
  590. outside of this function.
  591. """
  592. G_debug(1, self.get_bash())
  593. if self.inputs['stdin'].value:
  594. self.stdin = self.inputs['stdin'].value
  595. self.stdin_ = PIPE
  596. cmd = self.make_cmd()
  597. start = time.time()
  598. self.popen = Popen(cmd,
  599. stdin=self.stdin_,
  600. stdout=self.stdout_,
  601. stderr=self.stderr_,
  602. env=self.env_)
  603. if self.finish_:
  604. stdout, stderr = self.popen.communicate(input=self.stdin)
  605. self.outputs['stdout'].value = stdout if stdout else ''
  606. self.outputs['stderr'].value = stderr if stderr else ''
  607. self.time = time.time() - start
  608. if self.popen.poll():
  609. raise CalledModuleError(returncode=self.popen.returncode,
  610. code=self.get_bash(),
  611. module=self.name, errors=stderr)
  612. return self
  613. ###############################################################################
  614. if __name__ == "__main__":
  615. import doctest
  616. doctest.testmod()