__init__.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Thu Jul 12 10:23:15 2012
  4. @author: pietro
  5. """
  6. from __future__ import print_function
  7. import subprocess
  8. import fnmatch
  9. try:
  10. from collections import OrderedDict
  11. except ImportError:
  12. from pygrass.orderdict import OrderedDict
  13. from itertools import izip_longest
  14. from xml.etree.ElementTree import fromstring
  15. import grass
  16. #
  17. # this dictionary is used to extract the value of interest from the xml
  18. # the lambda experssion is used to define small simple functions,
  19. # is equivalent to: ::
  20. #
  21. # def f(p):
  22. # return p.text.strip()
  23. #
  24. # and then we call f(p)
  25. #
  26. _GETFROMTAG = {
  27. 'description': lambda p: p.text.strip(),
  28. 'keydesc': lambda p: p.text.strip(),
  29. 'gisprompt': lambda p: dict(p.items()),
  30. 'default': lambda p: p.text.strip(),
  31. 'values': lambda p: [e.text.strip() for e in p.findall('value/name')],
  32. 'value': lambda p: None,
  33. 'guisection': lambda p: p.text.strip(),
  34. 'label': lambda p: p.text.strip(),
  35. 'suppress_required': lambda p: None,
  36. 'keywords': lambda p: p.text.strip(),
  37. }
  38. _GETTYPE = {
  39. 'string': str,
  40. 'integer': int,
  41. 'float': float,
  42. 'double': float,
  43. }
  44. def stdout2dict(stdout, sep='=', default=None, val_type=None, vsep=None):
  45. """Return a dictionary where entries are separated
  46. by newlines and the key and value are separated by `sep' (default: `=').
  47. Use the grass.core.parse_key_val function
  48. sep: key/value separator
  49. default: default value to be used
  50. val_type: value type (None for no cast)
  51. vsep: vertical separator (default os.linesep)
  52. """
  53. return grass.script.core.parse_key_val(stdout, sep, default,
  54. val_type, vsep)
  55. class ParameterError(Exception):
  56. pass
  57. class FlagError(Exception):
  58. pass
  59. def _element2dict(xparameter):
  60. diz = dict(xparameter.items())
  61. for p in xparameter:
  62. if p.tag in _GETFROMTAG:
  63. diz[p.tag] = _GETFROMTAG[p.tag](p)
  64. else:
  65. print('New tag: %s, ignored' % p.tag)
  66. return diz
  67. # dictionary used to create docstring for the objects
  68. _DOC = {
  69. #------------------------------------------------------------
  70. # head
  71. 'head': """{cmd_name}({cmd_params})
  72. Parameters
  73. ----------
  74. """,
  75. #------------------------------------------------------------
  76. # param
  77. 'param': """{name}: {default}{required}{multi}{ptype}
  78. {description}{values}""",
  79. #------------------------------------------------------------
  80. # flag_head
  81. 'flag_head': """
  82. Flags
  83. ------
  84. """,
  85. #------------------------------------------------------------
  86. # flag
  87. 'flag': """{name}: {default}
  88. {description}""",
  89. #------------------------------------------------------------
  90. # foot
  91. 'foot': """
  92. Special Parameters
  93. ------------------
  94. The Module class have some optional parameters which are distinct using a final
  95. underscore.
  96. run_: True, optional
  97. If True execute the module.
  98. finish_: True, optional
  99. If True wait untill the end of the module execution, and store the module
  100. outputs into stdout, stderr attributes of the class.
  101. stdin_: PIPE,
  102. Set the standard input
  103. """}
  104. class Parameter(object):
  105. def __init__(self, xparameter=None, diz=None):
  106. self._value = None
  107. diz = _element2dict(xparameter) if xparameter is not None else diz
  108. if diz is None:
  109. raise TypeError('Xparameter or diz are required')
  110. self.name = diz['name']
  111. self.required = True if diz['required'] == 'yes' else False
  112. self.multiple = True if diz['multiple'] == 'yes' else False
  113. # check the type
  114. if diz['type'] in _GETTYPE:
  115. self.type = _GETTYPE[diz['type']]
  116. self.typedesc = diz['type']
  117. self._type = _GETTYPE[diz['type']]
  118. else:
  119. raise TypeError('New type: %s, ignored' % diz['type'])
  120. self.description = diz.get('description', None)
  121. self.keydesc = diz.get('keydesc', None)
  122. self.values = [self._type(
  123. i) for i in diz['values']] if 'values' in diz else None
  124. self.default = self._type(
  125. diz['default']) if 'default' in diz else None
  126. if self.default is not None:
  127. self._value = self.default
  128. self.guisection = diz.get('guisection', None)
  129. if 'gisprompt' in diz:
  130. self.type = diz['gisprompt']['prompt']
  131. self.input = False if diz['gisprompt']['age'] == 'new' else True
  132. else:
  133. self.input = True
  134. def _get_value(self):
  135. return self._value
  136. def _set_value(self, value):
  137. if isinstance(value, list) or isinstance(value, tuple):
  138. if self.multiple:
  139. # check each value
  140. self._value = [
  141. val for val in value if isinstance(value, self._type)]
  142. else:
  143. str_err = 'The Parameter <%s> does not accept multiple inputs'
  144. raise TypeError(str_err % self.name)
  145. elif isinstance(value, self._type):
  146. if self.values:
  147. if value in self.values:
  148. self._value = value
  149. else:
  150. raise ValueError('The Parameter <%s>, must be one of: %r' %
  151. (self.name, self.values))
  152. else:
  153. self._value = value
  154. else:
  155. str_err = 'The Parameter <%s>, require: %s, get: %s instead'
  156. raise TypeError(str_err % (self.name, self.typedesc, type(value)))
  157. # here the property function is used to transform value in an attribute
  158. # in this case we define which function must be use to get/set the value
  159. value = property(fget=_get_value, fset=_set_value)
  160. def get_bash(self):
  161. if isinstance(self._value, list) or isinstance(self._value, tuple):
  162. value = ','.join([str(v) for v in self._value])
  163. else:
  164. value = str(self._value)
  165. return """%s=%s""" % (self.name, value)
  166. def get_python(self):
  167. if not self.value:
  168. return ''
  169. return """%s=%r""" % (self.name, self._value)
  170. def __str__(self):
  171. return self.get_bash()
  172. def __repr__(self):
  173. str_repr = "Parameter <%s> (required:%s, type:%s, multiple:%s)"
  174. return str_repr % (self.name,
  175. "yes" if self.required else "no",
  176. self.type if self.type in (
  177. 'raster', 'vector') else self.typedesc,
  178. "yes" if self.multiple else "no")
  179. # here we use property with a decorator, in this way we mask a method as
  180. # a class attribute
  181. @property
  182. def __doc__(self):
  183. """Return the docstring of the parameter
  184. {name}: {default}{required}{multi}{ptype}
  185. {description}{values}"","""
  186. return _DOC['param'].format(name=self.name,
  187. default=repr(self.default) + ', ' if self.default else '',
  188. required='required, ' if self.required else 'optional, ',
  189. multi='multi' if self.multiple else '',
  190. ptype=self.typedesc, description=self.description,
  191. values='\n Values: {0}'.format(', '.join([repr(val)
  192. for val in self.values]))
  193. if self.values else '')
  194. class TypeDict(OrderedDict):
  195. def __init__(self, dict_type, *args, **kargs):
  196. self.type = dict_type
  197. super(TypeDict, self).__init__(*args, **kargs)
  198. def __setitem__(self, key, value):
  199. if isinstance(value, self.type):
  200. super(TypeDict, self).__setitem__(key, value)
  201. else:
  202. cl = repr(self.type).translate(None, "'<> ").split('.')
  203. str_err = 'The value: %r is not a %s object'
  204. raise TypeError(str_err % (value, cl[-1].title()))
  205. @property
  206. def __doc__(self):
  207. return '\n'.join([self.__getitem__(obj).__doc__
  208. for obj in self.__iter__()])
  209. def __call__(self):
  210. return [self.__getitem__(obj) for obj in self.__iter__()]
  211. class Flag(object):
  212. def __init__(self, xflag=None, diz=None):
  213. self.value = None
  214. diz = _element2dict(xflag) if xflag is not None else diz
  215. self.name = diz['name']
  216. self.special = True if self.name in (
  217. 'verbose', 'overwrite', 'quiet', 'run') else False
  218. self.description = diz['description']
  219. self.default = diz.get('default', None)
  220. self.guisection = diz.get('guisection', None)
  221. def get_bash(self):
  222. if self.value:
  223. if self.special:
  224. return '--%s' % self.name[0]
  225. else:
  226. return '-%s' % self.name
  227. else:
  228. return ''
  229. def get_python(self):
  230. if self.value:
  231. if self.special:
  232. return '%s=True' % self.name
  233. else:
  234. return self.name
  235. else:
  236. return ''
  237. def __str__(self):
  238. return self.get_bash()
  239. def __repr__(self):
  240. return "Flag <%s> (%s)" % (self.name, self.description)
  241. @property
  242. def __doc__(self):
  243. """
  244. {name}: {default}
  245. {description}"""
  246. return _DOC['flag'].format(name=self.name,
  247. default=repr(self.default),
  248. description=self.description)
  249. class Module(object):
  250. """
  251. Python allow developers to not specify all the arguments and
  252. keyword arguments of a method or function.
  253. ::
  254. def f(*args):
  255. for arg in args:
  256. print arg
  257. therefore if we call the function like: ::
  258. >>> f('grass', 'gis', 'modules')
  259. grass
  260. gis
  261. modules
  262. or we can define a new list: ::
  263. >>> words = ['grass', 'gis', 'modules']
  264. >>> f(*words)
  265. grass
  266. gis
  267. modules
  268. we can do the same with keyword arguments, rewrite the above function: ::
  269. def f(*args, **kargs):
  270. for arg in args:
  271. print arg
  272. for key, value in kargs.items():
  273. print "%s = %r" % (key, value)
  274. now we can use the new function, with: ::
  275. >>> f('grass', 'gis', 'modules', os = 'linux', language = 'python')
  276. grass
  277. gis
  278. modules
  279. os = 'linux'
  280. language = 'python'
  281. or, as before we can, define a dictionary and give the dictionary to
  282. the function, like: ::
  283. >>> keywords = {'os' : 'linux', 'language' : 'python'}
  284. >>> f(*words, **keywords)
  285. grass
  286. gis
  287. modules
  288. os = 'linux'
  289. language = 'python'
  290. In the Module class we heavily use this language feature to pass arguments
  291. and keyword arguments to the grass module.
  292. """
  293. def __init__(self, cmd, *args, **kargs):
  294. self.name = cmd
  295. # call the command with --interface-description
  296. get_cmd_xml = subprocess.Popen([cmd, "--interface-description"],
  297. stdout=subprocess.PIPE)
  298. # get the xml of the module
  299. self.xml = get_cmd_xml.communicate()[0]
  300. # transform and parse the xml into an Element class:
  301. # http://docs.python.org/library/xml.etree.elementtree.html
  302. tree = fromstring(self.xml)
  303. for e in tree:
  304. if e.tag not in ('parameter', 'flag'):
  305. self.__setattr__(e.tag, _GETFROMTAG[e.tag](e))
  306. #
  307. # extract parameters from the xml
  308. #
  309. self.params_list = [Parameter(p) for p in tree.findall("parameter")]
  310. self.inputs = TypeDict(Parameter)
  311. self.outputs = TypeDict(Parameter)
  312. self.required = []
  313. # Insert parameters into input/output and required
  314. for par in self.params_list:
  315. if par.input:
  316. self.inputs[par.name] = par
  317. else:
  318. self.outputs[par.name] = par
  319. if par.required:
  320. self.required.append(par)
  321. #
  322. # extract flags from the xml
  323. #
  324. flags_list = [Flag(f) for f in tree.findall("flag")]
  325. self.flags_dict = TypeDict(Flag)
  326. for flag in flags_list:
  327. self.flags_dict[flag.name] = flag
  328. #
  329. # Add new attributes to the class
  330. #
  331. self.run_ = True
  332. self.finish_ = True
  333. self.stdin_ = None
  334. self.stdout_ = None
  335. self.stderr_ = None
  336. self.popen = None
  337. if args or kargs:
  338. self.__call__(*args, **kargs)
  339. def _get_flags(self):
  340. return ''.join([flg.get_python() for flg in self.flags_dict.values()
  341. if not flg.special])
  342. def _set_flags(self, value):
  343. if isinstance(value, str):
  344. if value == '':
  345. for flg in self.flags_dict.values():
  346. if not flg.special:
  347. flg.value = False
  348. else:
  349. flgs = [flg.name for flg in self.flags_dict.values()
  350. if not flg.special]
  351. # we need to check if the flag is valid, special flags are not
  352. # allow
  353. for val in value:
  354. if val in flgs:
  355. self.flags_dict[val].value = True
  356. else:
  357. str_err = 'Flag not valid: %r, valid flag are: %r'
  358. raise ValueError(str_err % (val, flgs))
  359. else:
  360. raise TypeError('The flags attribute must be a string')
  361. flags = property(fget=_get_flags, fset=_set_flags)
  362. def __call__(self, *args, **kargs):
  363. if not args and not kargs:
  364. self.run()
  365. return
  366. #
  367. # check for extra kargs, set attribute and remove from dictionary
  368. #
  369. if 'flags' in kargs:
  370. self.flags = kargs['flags']
  371. del(kargs['flags'])
  372. if 'run_' in kargs:
  373. self.run_ = kargs['run_']
  374. del(kargs['run_'])
  375. if 'stdin_' in kargs:
  376. self.stdin_ = kargs['stdin_']
  377. del(kargs['stdin_'])
  378. if 'stdout_' in kargs:
  379. self.stdout_ = kargs['stdout_']
  380. del(kargs['stdout_'])
  381. if 'stderr_' in kargs:
  382. self.stderr_ = kargs['stderr_']
  383. del(kargs['stderr_'])
  384. if 'finish_' in kargs:
  385. self.finish_ = kargs['finish_']
  386. del(kargs['finish_'])
  387. #
  388. # check args
  389. #
  390. for param, arg in zip(self.params_list, args):
  391. param.value = arg
  392. for key, val in kargs.items():
  393. if key in self.inputs:
  394. self.inputs[key].value = val
  395. elif key in self.outputs:
  396. self.outputs[key].value = val
  397. elif key in self.flags_dict:
  398. # we need to add this, because some parameters (overwrite,
  399. # verbose and quiet) work like parameters
  400. self.flags_dict[key].value = val
  401. else:
  402. raise ParameterError('%s is not a valid parameter.' % key)
  403. #
  404. # check reqire parameters
  405. #
  406. for par in self.required:
  407. if par.value is None:
  408. raise ParameterError(
  409. "Required parameter <%s> not set." % par.name)
  410. #
  411. # check flags parameters
  412. #
  413. if self.flags:
  414. # check each character in flags
  415. for flag in self.flags:
  416. if flag in self.flags_dict:
  417. self.flags_dict[flag].value = True
  418. else:
  419. raise FlagError('Flag "%s" not valid.' % flag)
  420. #
  421. # check if execute
  422. #
  423. if self.run_:
  424. self.run()
  425. def get_bash(self):
  426. return ' '.join(self.make_cmd())
  427. def get_python(self):
  428. prefix = self.name.split('.')[0]
  429. name = '_'.join(self.name.split('.')[1:])
  430. params = ', '.join([par.get_python() for par in self.params_list
  431. if par.get_python() != ''])
  432. special = ', '.join([flg.get_python()
  433. for flg in self.flags_dict.values()
  434. if flg.special and flg.get_python() != ''])
  435. # pre name par flg special
  436. if self.flags and special:
  437. return "%s.%s(%s, flags=%r, %s)" % (prefix, name, params,
  438. self.flags, special)
  439. elif self.flags:
  440. return "%s.%s(%s, flags=%r)" % (prefix, name, params, self.flags)
  441. elif special:
  442. return "%s.%s(%s, %s)" % (prefix, name, params, special)
  443. else:
  444. return "%s.%s(%s)" % (prefix, name, params)
  445. def __str__(self):
  446. return ' '.join(self.make_cmd())
  447. @property
  448. def __doc__(self):
  449. """{cmd_name}({cmd_params})
  450. """
  451. head = _DOC['head'].format(cmd_name=self.name,
  452. cmd_params=('\n' + # go to a new line
  453. # give space under the function name
  454. (' ' * (len(self.name) + 1))).join([', '.join(
  455. # transform each parameter in string
  456. [str(param) for param in line if param is not None])
  457. # make a list of parameters with only 3 param per line
  458. for line in izip_longest(*[iter(self.params_list)] * 3)]),)
  459. params = '\n'.join([par.__doc__ for par in self.params_list])
  460. flags = self.flags_dict.__doc__
  461. return '\n'.join([head, params, _DOC['flag_head'], flags])
  462. def make_cmd(self):
  463. args = [self.name, ]
  464. for par in self.params_list:
  465. if par.value is not None:
  466. args.append(str(par))
  467. for flg in self.flags_dict:
  468. if self.flags_dict[flg].value:
  469. args.append(str(self.flags_dict[flg]))
  470. return args
  471. def run(self, node=None):
  472. cmd = self.make_cmd()
  473. self.popen = subprocess.Popen(cmd, stdin=self.stdin_,
  474. stdout=self.stdout_,
  475. stderr=self.stderr_)
  476. if self.finish_:
  477. self.popen.wait()
  478. self.stdout, self.stderr = self.popen.communicate()
  479. _CMDS = list(grass.script.core.get_commands()[0])
  480. _CMDS.sort()
  481. class MetaModule(object):
  482. def __init__(self, prefix):
  483. self.prefix = prefix
  484. def __dir__(self):
  485. return [mod[(len(self.prefix) + 1):].replace('.', '_')
  486. for mod in fnmatch.filter(_CMDS, "%s.*" % self.prefix)]
  487. def __getattr__(self, name):
  488. return Module('%s.%s' % (self.prefix, name.replace('_', '.')))
  489. # http://grass.osgeo.org/grass70/manuals/html70_user/full_index.html
  490. #[ d.* | db.* | g.* | i.* | m.* | ps.* | r.* | r3.* | t.* | v.* ]
  491. #
  492. # d.* display commands
  493. # db.* database commands
  494. # g.* general commands
  495. # i.* imagery commands
  496. # m.* miscellaneous commands
  497. # ps.* postscript commands
  498. # r.* raster commands
  499. # r3.* raster3D commands
  500. # t.* temporal commands
  501. # v.* vector commands
  502. display = MetaModule('d')
  503. database = MetaModule('db')
  504. general = MetaModule('g')
  505. imagery = MetaModule('i')
  506. miscellaneous = MetaModule('m')
  507. postscript = MetaModule('ps')
  508. raster = MetaModule('r')
  509. raster3D = MetaModule('r3')
  510. temporal = MetaModule('t')
  511. vector = MetaModule('v')