utils.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. # -*- coding: utf-8 -*-
  2. """
  3. Useful functions to be used in Python scripts.
  4. Usage:
  5. ::
  6. from grass.script import utils as gutils
  7. (C) 2014-2016 by the GRASS Development Team
  8. This program is free software under the GNU General Public
  9. License (>=v2). Read the file COPYING that comes with GRASS
  10. for details.
  11. .. sectionauthor:: Glynn Clements
  12. .. sectionauthor:: Martin Landa <landa.martin gmail.com>
  13. .. sectionauthor:: Anna Petrasova <kratochanna gmail.com>
  14. """
  15. import os
  16. import sys
  17. import shutil
  18. import locale
  19. import shlex
  20. import re
  21. try:
  22. from builtins import unicode
  23. except ImportError:
  24. # python3
  25. unicode = str
  26. def float_or_dms(s):
  27. """Convert DMS to float.
  28. >>> round(float_or_dms('26:45:30'), 5)
  29. 26.75833
  30. >>> round(float_or_dms('26:0:0.1'), 5)
  31. 26.00003
  32. :param s: DMS value
  33. :return: float value
  34. """
  35. return sum(float(x) / 60 ** n for (n, x) in enumerate(s.split(':')))
  36. def separator(sep):
  37. """Returns separator from G_OPT_F_SEP appropriately converted
  38. to character.
  39. >>> separator('pipe')
  40. '|'
  41. >>> separator('comma')
  42. ','
  43. If the string does not match any of the separator keywords,
  44. it is returned as is:
  45. >>> separator(', ')
  46. ', '
  47. :param str separator: character or separator keyword
  48. :return: separator character
  49. """
  50. if sep == "pipe":
  51. return "|"
  52. elif sep == "comma":
  53. return ","
  54. elif sep == "space":
  55. return " "
  56. elif sep == "tab" or sep == "\\t":
  57. return "\t"
  58. elif sep == "newline" or sep == "\\n":
  59. return "\n"
  60. return sep
  61. def diff_files(filename_a, filename_b):
  62. """Diffs two text files and returns difference.
  63. :param str filename_a: first file path
  64. :param str filename_b: second file path
  65. :return: list of strings
  66. """
  67. import difflib
  68. differ = difflib.Differ()
  69. fh_a = open(filename_a, 'r')
  70. fh_b = open(filename_b, 'r')
  71. result = list(differ.compare(fh_a.readlines(),
  72. fh_b.readlines()))
  73. return result
  74. def try_remove(path):
  75. """Attempt to remove a file; no exception is generated if the
  76. attempt fails.
  77. :param str path: path to file to remove
  78. """
  79. try:
  80. os.remove(path)
  81. except:
  82. pass
  83. def try_rmdir(path):
  84. """Attempt to remove a directory; no exception is generated if the
  85. attempt fails.
  86. :param str path: path to directory to remove
  87. """
  88. try:
  89. os.rmdir(path)
  90. except:
  91. shutil.rmtree(path, ignore_errors=True)
  92. def basename(path, ext=None):
  93. """Remove leading directory components and an optional extension
  94. from the specified path
  95. :param str path: path
  96. :param str ext: extension
  97. """
  98. name = os.path.basename(path)
  99. if not ext:
  100. return name
  101. fs = name.rsplit('.', 1)
  102. if len(fs) > 1 and fs[1].lower() == ext:
  103. name = fs[0]
  104. return name
  105. class KeyValue(dict):
  106. """A general-purpose key-value store.
  107. KeyValue is a subclass of dict, but also allows entries to be read and
  108. written using attribute syntax. Example:
  109. >>> reg = KeyValue()
  110. >>> reg['north'] = 489
  111. >>> reg.north
  112. 489
  113. >>> reg.south = 205
  114. >>> reg['south']
  115. 205
  116. """
  117. def __getattr__(self, key):
  118. return self[key]
  119. def __setattr__(self, key, value):
  120. self[key] = value
  121. def _get_encoding():
  122. encoding = locale.getdefaultlocale()[1]
  123. if not encoding:
  124. encoding = 'UTF-8'
  125. return encoding
  126. def decode(bytes_):
  127. """Decode bytes with default locale and return (unicode) string
  128. No-op if parameter is not bytes (assumed unicode string).
  129. :param bytes bytes_: the bytes to decode
  130. Example
  131. -------
  132. >>> decode(b'S\xc3\xbcdtirol')
  133. u'Südtirol'
  134. >>> decode(u'Südtirol')
  135. u'Südtirol'
  136. >>> decode(1234)
  137. u'1234'
  138. """
  139. if isinstance(bytes_, unicode):
  140. return bytes_
  141. if isinstance(bytes_, bytes):
  142. enc = _get_encoding()
  143. return bytes_.decode(enc)
  144. return unicode(bytes_)
  145. def encode(string):
  146. """Encode string with default locale and return bytes with that encoding
  147. No-op if parameter is bytes (assumed already encoded).
  148. This ensures garbage in, garbage out.
  149. :param str string: the string to encode
  150. Example
  151. -------
  152. >>> encode(b'S\xc3\xbcdtirol')
  153. b'S\xc3\xbcdtirol'
  154. >>> decode(u'Südtirol')
  155. b'S\xc3\xbcdtirol'
  156. >>> decode(1234)
  157. b'1234'
  158. """
  159. if isinstance(string, bytes):
  160. return string
  161. if isinstance(string, unicode):
  162. enc = _get_encoding()
  163. return string.encode(enc)
  164. return bytes(string)
  165. def parse_key_val(s, sep='=', dflt=None, val_type=None, vsep=None):
  166. """Parse a string into a dictionary, where entries are separated
  167. by newlines and the key and value are separated by `sep` (default: `=`)
  168. >>> parse_key_val('min=20\\nmax=50') == {'min': '20', 'max': '50'}
  169. True
  170. >>> parse_key_val('min=20\\nmax=50',
  171. ... val_type=float) == {'min': 20, 'max': 50}
  172. True
  173. :param str s: string to be parsed
  174. :param str sep: key/value separator
  175. :param dflt: default value to be used
  176. :param val_type: value type (None for no cast)
  177. :param vsep: vertical separator (default is Python 'universal newlines' approach)
  178. :return: parsed input (dictionary of keys/values)
  179. """
  180. result = KeyValue()
  181. if not s:
  182. return result
  183. if isinstance(s, bytes):
  184. sep = encode(sep)
  185. vsep = encode(vsep) if vsep else vsep
  186. if vsep:
  187. lines = s.split(vsep)
  188. try:
  189. lines.remove('\n')
  190. except ValueError:
  191. pass
  192. else:
  193. lines = s.splitlines()
  194. for line in lines:
  195. kv = line.split(sep, 1)
  196. k = decode(kv[0].strip())
  197. if len(kv) > 1:
  198. v = decode(kv[1].strip())
  199. else:
  200. v = dflt
  201. if val_type:
  202. result[k] = val_type(v)
  203. else:
  204. result[k] = v
  205. return result
  206. def get_num_suffix(number, max_number):
  207. """Returns formatted number with number of padding zeros
  208. depending on maximum number, used for creating suffix for data series.
  209. Does not include the suffix separator.
  210. :param number: number to be formatted as map suffix
  211. :param max_number: maximum number of the series to get number of digits
  212. >>> get_num_suffix(10, 1000)
  213. '0010'
  214. >>> get_num_suffix(10, 10)
  215. '10'
  216. """
  217. return '{number:0{width}d}'.format(width=len(str(max_number)),
  218. number=number)
  219. def split(s):
  220. """!Platform specific shlex.split"""
  221. if sys.version_info >= (2, 6):
  222. return shlex.split(s, posix = (sys.platform != "win32"))
  223. elif sys.platform == "win32":
  224. return shlex.split(s.replace('\\', r'\\'))
  225. else:
  226. return shlex.split(s)
  227. # source:
  228. # http://stackoverflow.com/questions/4836710/
  229. # does-python-have-a-built-in-function-for-string-natural-sort/4836734#4836734
  230. def natural_sort(l):
  231. """Returns sorted strings using natural sort
  232. """
  233. convert = lambda text: int(text) if text.isdigit() else text.lower()
  234. alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
  235. return sorted(l, key=alphanum_key)
  236. def get_lib_path(modname, libname=None):
  237. """Return the path of the libname contained in the module.
  238. """
  239. from os.path import isdir, join, sep
  240. from os import getenv
  241. if isdir(join(getenv('GISBASE'), 'etc', modname)):
  242. path = join(os.getenv('GISBASE'), 'etc', modname)
  243. elif getenv('GRASS_ADDON_BASE') and libname and \
  244. isdir(join(getenv('GRASS_ADDON_BASE'), 'etc', modname, libname)):
  245. path = join(getenv('GRASS_ADDON_BASE'), 'etc', modname)
  246. elif getenv('GRASS_ADDON_BASE') and \
  247. isdir(join(getenv('GRASS_ADDON_BASE'), 'etc', modname)):
  248. path = join(getenv('GRASS_ADDON_BASE'), 'etc', modname)
  249. elif getenv('GRASS_ADDON_BASE') and \
  250. isdir(join(getenv('GRASS_ADDON_BASE'), modname, modname)):
  251. path = join(os.getenv('GRASS_ADDON_BASE'), modname, modname)
  252. else:
  253. # used by g.extension compilation process
  254. cwd = os.getcwd()
  255. idx = cwd.find(modname)
  256. if idx < 0:
  257. return None
  258. path = '{cwd}{sep}etc{sep}{modname}'.format(cwd=cwd[:idx+len(modname)],
  259. sep=sep,
  260. modname=modname)
  261. if libname:
  262. path += '{pathsep}{cwd}{sep}etc{sep}{modname}{sep}{libname}'.format(
  263. cwd=cwd[:idx+len(modname)],
  264. sep=sep,
  265. modname=modname, libname=libname,
  266. pathsep=os.pathsep
  267. )
  268. return path
  269. def set_path(modulename, dirname=None, path='.'):
  270. """Set sys.path looking in the the local directory GRASS directories.
  271. :param modulename: string with the name of the GRASS module
  272. :param dirname: string with the directory name containing the python
  273. libraries, default None
  274. :param path: string with the path to reach the dirname locally.
  275. Example
  276. --------
  277. "set_path" example working locally with the source code of a module
  278. (r.green) calling the function with all the parameters. Below it is
  279. reported the directory structure on the r.green module.
  280. ::
  281. grass_prompt> pwd
  282. ~/Download/r.green/r.green.hydro/r.green.hydro.financial
  283. grass_prompt> tree ../../../r.green
  284. ../../../r.green
  285. |-- ...
  286. |-- libgreen
  287. | |-- pyfile1.py
  288. | +-- pyfile2.py
  289. +-- r.green.hydro
  290. |-- Makefile
  291. |-- libhydro
  292. | |-- pyfile1.py
  293. | +-- pyfile2.py
  294. |-- r.green.hydro.*
  295. +-- r.green.hydro.financial
  296. |-- Makefile
  297. |-- ...
  298. +-- r.green.hydro.financial.py
  299. 21 directories, 125 files
  300. in the source code the function is called with the following parameters: ::
  301. set_path('r.green', 'libhydro', '..')
  302. set_path('r.green', 'libgreen', os.path.join('..', '..'))
  303. when we are executing the module: r.green.hydro.financial locally from
  304. the command line: ::
  305. grass_prompt> python r.green.hydro.financial.py --ui
  306. In this way we are executing the local code even if the module was already
  307. installed as grass-addons and it is available in GRASS standards path.
  308. The function is cheching if the dirname is provided and if the
  309. directory exists and it is available using the path
  310. provided as third parameter, if yes add the path to sys.path to be
  311. importable, otherwise it will check on GRASS GIS standard paths.
  312. """
  313. import sys
  314. # TODO: why dirname is checked first - the logic should be revised
  315. pathlib = None
  316. if dirname:
  317. pathlib = os.path.join(path, dirname)
  318. if pathlib and os.path.exists(pathlib):
  319. # we are running the script from the script directory, therefore
  320. # we add the path to sys.path to reach the directory (dirname)
  321. sys.path.append(os.path.abspath(path))
  322. else:
  323. # running from GRASS GIS session
  324. path = get_lib_path(modulename, dirname)
  325. if path is None:
  326. pathname = os.path.join(modulename, dirname) if dirname else modulename
  327. raise ImportError("Not able to find the path '%s' directory "
  328. "(current dir '%s')." % (pathname, os.getcwd()))
  329. sys.path.insert(0, path)