__init__.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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. self.guisection = diz.get('guisection', None)
  127. if 'gisprompt' in diz:
  128. self.type = diz['gisprompt']['prompt']
  129. self.input = False if diz['gisprompt']['age'] == 'new' else True
  130. else:
  131. self.input = True
  132. def _get_value(self):
  133. return self._value
  134. def _set_value(self, value):
  135. if isinstance(value, list) or isinstance(value, tuple):
  136. if self.multiple:
  137. # check each value
  138. self._value = [
  139. val for val in value if isinstance(value, self._type)]
  140. else:
  141. str_err = 'The Parameter <%s>, not support multiple inputs'
  142. raise TypeError(str_err % self.name)
  143. elif isinstance(value, self._type):
  144. if self.values:
  145. if value in self.values:
  146. self._value = value
  147. else:
  148. raise ValueError('The Parameter <%s>, must be one of: %r' %
  149. (self.name, self.values))
  150. else:
  151. self._value = value
  152. else:
  153. str_err = 'The Parameter <%s>, require: %s, get: %s instead'
  154. raise TypeError(str_err % (self.name, self.typedesc, type(value)))
  155. # here the property function is used to transform value in an attribute
  156. # in this case we define which function must be use to get/set the value
  157. value = property(fget=_get_value, fset=_set_value)
  158. def get_bash(self):
  159. if isinstance(self._value, list) or isinstance(self._value, tuple):
  160. value = ','.join([str(v) for v in self._value])
  161. else:
  162. value = str(self._value)
  163. return """%s=%s""" % (self.name, value)
  164. def get_python(self):
  165. if not self.value:
  166. return ''
  167. return """%s=%r""" % (self.name, self._value)
  168. def __str__(self):
  169. return self.get_bash()
  170. def __repr__(self):
  171. str_repr = "Parameter <%s> (required:%s, type:%s, multiple:%s)"
  172. return str_repr % (self.name,
  173. "yes" if self.required else "no",
  174. self.type if self.type in (
  175. 'raster', 'vector') else self.typedesc,
  176. "yes" if self.multiple else "no")
  177. # here we use property with a decorator, in this way we mask a method as
  178. # a class attribute
  179. @property
  180. def __doc__(self):
  181. """Return the docstring of the parameter
  182. {name}: {default}{required}{multi}{ptype}
  183. {description}{values}"","""
  184. return _DOC['param'].format(name=self.name,
  185. default=repr(self.default) + ', ' if self.default else '',
  186. required='required, ' if self.required else 'optional, ',
  187. multi='multi' if self.multiple else '',
  188. ptype=self.typedesc, description=self.description,
  189. values='\n Values: {0}'.format(', '.join([repr(val)
  190. for val in self.values]))
  191. if self.values else '')
  192. class TypeDict(OrderedDict):
  193. def __init__(self, dict_type, *args, **kargs):
  194. self.type = dict_type
  195. super(TypeDict, self).__init__(*args, **kargs)
  196. def __setitem__(self, key, value):
  197. if isinstance(value, self.type):
  198. super(TypeDict, self).__setitem__(key, value)
  199. else:
  200. cl = repr(self.type).translate(None, "'<> ").split('.')
  201. str_err = 'The value: %r is not a %s object'
  202. raise TypeError(str_err % (value, cl[-1].title()))
  203. @property
  204. def __doc__(self):
  205. return '\n'.join([self.__getitem__(obj).__doc__
  206. for obj in self.__iter__()])
  207. def __call__(self):
  208. return [self.__getitem__(obj) for obj in self.__iter__()]
  209. class Flag(object):
  210. def __init__(self, xflag=None, diz=None):
  211. self.value = None
  212. diz = _element2dict(xflag) if xflag is not None else diz
  213. self.name = diz['name']
  214. self.special = True if self.name in (
  215. 'verbose', 'overwrite', 'quiet', 'run') else False
  216. self.description = diz['description']
  217. self.default = diz.get('default', None)
  218. self.guisection = diz.get('guisection', None)
  219. def get_bash(self):
  220. if self.value:
  221. if self.special:
  222. return '--%s' % self.name[0]
  223. else:
  224. return '-%s' % self.name
  225. else:
  226. return ''
  227. def get_python(self):
  228. if self.value:
  229. if self.special:
  230. return '%s=True' % self.name
  231. else:
  232. return self.name
  233. else:
  234. return ''
  235. def __str__(self):
  236. return self.get_bash()
  237. def __repr__(self):
  238. return "Flag <%s> (%s)" % (self.name, self.description)
  239. @property
  240. def __doc__(self):
  241. """
  242. {name}: {default}
  243. {description}"""
  244. return _DOC['flag'].format(name=self.name,
  245. default=repr(self.default),
  246. description=self.description)
  247. class Module(object):
  248. """
  249. Python allow developers to not specify all the arguments and
  250. keyword arguments of a method or function.
  251. ::
  252. def f(*args):
  253. for arg in args:
  254. print arg
  255. therefore if we call the function like: ::
  256. >>> f('grass', 'gis', 'modules')
  257. grass
  258. gis
  259. modules
  260. or we can define a new list: ::
  261. >>> words = ['grass', 'gis', 'modules']
  262. >>> f(*words)
  263. grass
  264. gis
  265. modules
  266. we can do the same with keyword arguments, rewrite the above function: ::
  267. def f(*args, **kargs):
  268. for arg in args:
  269. print arg
  270. for key, value in kargs.items():
  271. print "%s = %r" % (key, value)
  272. now we can use the new function, with: ::
  273. >>> f('grass', 'gis', 'modules', os = 'linux', language = 'python')
  274. grass
  275. gis
  276. modules
  277. os = 'linux'
  278. language = 'python'
  279. or, as before we can, define a dictionary and give the dictionary to
  280. the function, like: ::
  281. >>> keywords = {'os' : 'linux', 'language' : 'python'}
  282. >>> f(*words, **keywords)
  283. grass
  284. gis
  285. modules
  286. os = 'linux'
  287. language = 'python'
  288. In the Module class we heavily use this language feature to pass arguments
  289. and keyword arguments to the grass module.
  290. """
  291. def __init__(self, cmd, *args, **kargs):
  292. self.name = cmd
  293. # call the command with --interface-description
  294. get_cmd_xml = subprocess.Popen([cmd, "--interface-description"],
  295. stdout=subprocess.PIPE)
  296. # get the xml of the module
  297. self.xml = get_cmd_xml.communicate()[0]
  298. # transform and parse the xml into an Element class:
  299. # http://docs.python.org/library/xml.etree.elementtree.html
  300. tree = fromstring(self.xml)
  301. for e in tree:
  302. if e.tag not in ('parameter', 'flag'):
  303. self.__setattr__(e.tag, _GETFROMTAG[e.tag](e))
  304. #
  305. # extract parameters from the xml
  306. #
  307. self.params_list = [Parameter(p) for p in tree.findall("parameter")]
  308. self.inputs = TypeDict(Parameter)
  309. self.outputs = TypeDict(Parameter)
  310. self.required = []
  311. # Insert parameters into input/output and required
  312. for par in self.params_list:
  313. if par.input:
  314. self.inputs[par.name] = par
  315. else:
  316. self.outputs[par.name] = par
  317. if par.required:
  318. self.required.append(par)
  319. #
  320. # extract flags from the xml
  321. #
  322. flags_list = [Flag(f) for f in tree.findall("flag")]
  323. self.flags_dict = TypeDict(Flag)
  324. for flag in flags_list:
  325. self.flags_dict[flag.name] = flag
  326. #
  327. # Add new attributes to the class
  328. #
  329. self.run_ = True
  330. self.finish_ = True
  331. self.stdin_ = None
  332. self.stdout_ = None
  333. self.stderr_ = None
  334. self.popen = None
  335. if args or kargs:
  336. self.__call__(*args, **kargs)
  337. def _get_flags(self):
  338. return ''.join([flg.get_python() for flg in self.flags_dict.values()
  339. if not flg.special])
  340. def _set_flags(self, value):
  341. if isinstance(value, str):
  342. if value == '':
  343. for flg in self.flags_dict.values():
  344. if not flg.special:
  345. flg.value = False
  346. else:
  347. flgs = [flg.name for flg in self.flags_dict.values()
  348. if not flg.special]
  349. # we need to check if the flag is valid, special flags are not
  350. # allow
  351. for val in value:
  352. if val in flgs:
  353. self.flags_dict[val].value = True
  354. else:
  355. str_err = 'Flag not valid: %r, valid flag are: %r'
  356. raise ValueError(str_err % (val, flgs))
  357. else:
  358. raise TypeError('The flags attribute must be a string')
  359. flags = property(fget=_get_flags, fset=_set_flags)
  360. def __call__(self, *args, **kargs):
  361. if not args and not kargs:
  362. self.run()
  363. return
  364. #
  365. # check for extra kargs, set attribute and remove from dictionary
  366. #
  367. if 'flags' in kargs:
  368. self.flags = kargs['flags']
  369. del(kargs['flags'])
  370. if 'run_' in kargs:
  371. self.run_ = kargs['run_']
  372. del(kargs['run_'])
  373. if 'stdin_' in kargs:
  374. self.stdin_ = kargs['stdin_']
  375. del(kargs['stdin_'])
  376. if 'stdout_' in kargs:
  377. self.stdout_ = kargs['stdout_']
  378. del(kargs['stdout_'])
  379. if 'stderr_' in kargs:
  380. self.stderr_ = kargs['stderr_']
  381. del(kargs['stderr_'])
  382. if 'finish_' in kargs:
  383. self.finish_ = kargs['finish_']
  384. del(kargs['finish_'])
  385. #
  386. # check args
  387. #
  388. for param, arg in zip(self.params_list, args):
  389. param.value = arg
  390. for key, val in kargs.items():
  391. if key in self.inputs:
  392. self.inputs[key].value = val
  393. elif key in self.outputs:
  394. self.outputs[key].value = val
  395. elif key in self.flags_dict:
  396. # we need to add this, because some parameters (overwrite,
  397. # verbose and quiet) work like parameters
  398. self.flags_dict[key].value = val
  399. else:
  400. raise ParameterError('Parameter not found')
  401. #
  402. # check reqire parameters
  403. #
  404. for par in self.required:
  405. if par.value is None:
  406. raise ParameterError(
  407. "Required parameter <%s> not set." % par.name)
  408. #
  409. # check flags parameters
  410. #
  411. if self.flags:
  412. # check each character in flags
  413. for flag in self.flags:
  414. if flag in self.flags_dict:
  415. self.flags_dict[flag].value = True
  416. else:
  417. raise FlagError('Flag "%s" not valid.' % flag)
  418. #
  419. # check if execute
  420. #
  421. if self.run_:
  422. self.run()
  423. def get_bash(self):
  424. return ' '.join(self.make_cmd())
  425. def get_python(self):
  426. prefix = self.name.split('.')[0]
  427. name = '_'.join(self.name.split('.')[1:])
  428. params = ', '.join([par.get_python() for par in self.params_list
  429. if par.get_python() != ''])
  430. special = ', '.join([flg.get_python()
  431. for flg in self.flags_dict.values()
  432. if flg.special and flg.get_python() != ''])
  433. # pre name par flg special
  434. if self.flags and special:
  435. return "%s.%s(%s, flags=%r, %s)" % (prefix, name, params,
  436. self.flags, special)
  437. elif self.flags:
  438. return "%s.%s(%s, flags=%r)" % (prefix, name, params, self.flags)
  439. elif special:
  440. return "%s.%s(%s, %s)" % (prefix, name, params, special)
  441. else:
  442. return "%s.%s(%s)" % (prefix, name, params)
  443. def __str__(self):
  444. return ' '.join(self.make_cmd())
  445. @property
  446. def __doc__(self):
  447. """{cmd_name}({cmd_params})
  448. """
  449. head = _DOC['head'].format(cmd_name=self.name,
  450. cmd_params=('\n' + # go to a new line
  451. # give space under the function name
  452. (' ' * (len(self.name) + 1))).join([', '.join(
  453. # transform each parameter in string
  454. [str(param) for param in line if param is not None])
  455. # make a list of parameters with only 3 param per line
  456. for line in izip_longest(*[iter(self.params_list)] * 3)]),)
  457. params = '\n'.join([par.__doc__ for par in self.params_list])
  458. flags = self.flags_dict.__doc__
  459. return '\n'.join([head, params, _DOC['flag_head'], flags])
  460. def make_cmd(self):
  461. args = [self.name, ]
  462. for par in self.params_list:
  463. if par.value is not None:
  464. args.append(str(par))
  465. for flg in self.flags_dict:
  466. if self.flags_dict[flg].value:
  467. args.append(str(self.flags_dict[flg]))
  468. return args
  469. def run(self, node=None):
  470. cmd = self.make_cmd()
  471. self.popen = subprocess.Popen(cmd, stdin=self.stdin_,
  472. stdout=self.stdout_,
  473. stderr=self.stderr_)
  474. if self.finish_:
  475. self.popen.wait()
  476. self.stdout, self.stderr = self.popen.communicate()
  477. _CMDS = list(grass.script.core.get_commands()[0])
  478. _CMDS.sort()
  479. class MetaModule(object):
  480. def __init__(self, prefix):
  481. self.prefix = prefix
  482. def __dir__(self):
  483. return [mod[(len(self.prefix) + 1):].replace('.', '_')
  484. for mod in fnmatch.filter(_CMDS, "%s.*" % self.prefix)]
  485. def __getattr__(self, name):
  486. return Module('%s.%s' % (self.prefix, name.replace('_', '.')))
  487. # http://grass.osgeo.org/grass70/manuals/html70_user/full_index.html
  488. #[ d.* | db.* | g.* | i.* | m.* | ps.* | r.* | r3.* | t.* | v.* ]
  489. #
  490. # d.* display commands
  491. # db.* database commands
  492. # g.* general commands
  493. # i.* imagery commands
  494. # m.* miscellaneous commands
  495. # ps.* postscript commands
  496. # r.* raster commands
  497. # r3.* raster3D commands
  498. # t.* temporal commands
  499. # v.* vector commands
  500. display = MetaModule('d')
  501. database = MetaModule('db')
  502. general = MetaModule('g')
  503. imagery = MetaModule('i')
  504. miscellaneous = MetaModule('m')
  505. postscript = MetaModule('ps')
  506. raster = MetaModule('r')
  507. raster3D = MetaModule('r3')
  508. temporal = MetaModule('t')
  509. vector = MetaModule('v')