utils.py 11 KB

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