utils.py 11 KB

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