utils.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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_, encoding=None):
  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. :param encoding: encoding to be used, default value is None
  128. Example
  129. -------
  130. >>> decode(b'S\xc3\xbcdtirol')
  131. u'Südtirol'
  132. >>> decode(u'Südtirol')
  133. u'Südtirol'
  134. >>> decode(1234)
  135. u'1234'
  136. """
  137. if isinstance(bytes_, unicode):
  138. return bytes_
  139. if isinstance(bytes_, bytes):
  140. if encoding is None:
  141. enc = _get_encoding()
  142. else:
  143. enc = encoding
  144. return bytes_.decode(enc)
  145. # if something else than text
  146. if sys.version_info.major >= 3:
  147. # only text should be used
  148. raise TypeError("can only accept types str and bytes")
  149. else:
  150. # for backwards compatibility
  151. return unicode(bytes_)
  152. def encode(string, encoding=None):
  153. """Encode string with default locale and return bytes with that encoding
  154. No-op if parameter is bytes (assumed already encoded).
  155. This ensures garbage in, garbage out.
  156. :param str string: the string to encode
  157. :param encoding: encoding to be used, default value is None
  158. Example
  159. -------
  160. >>> encode(b'S\xc3\xbcdtirol')
  161. b'S\xc3\xbcdtirol'
  162. >>> decode(u'Südtirol')
  163. b'S\xc3\xbcdtirol'
  164. >>> decode(1234)
  165. b'1234'
  166. """
  167. if isinstance(string, bytes):
  168. return string
  169. # this also tests str in Py3:
  170. if isinstance(string, unicode):
  171. if encoding is None:
  172. enc = _get_encoding()
  173. else:
  174. enc = encoding
  175. return string.encode(enc)
  176. # if something else than text
  177. if sys.version_info.major >= 3:
  178. # only text should be used
  179. raise TypeError("can only accept types str and bytes")
  180. else:
  181. # for backwards compatibility
  182. return bytes(string)
  183. def text_to_string(text, encoding=None):
  184. """Convert text to str. Useful when passing text into environments,
  185. in Python 2 it needs to be bytes on Windows, in Python 3 in needs unicode.
  186. """
  187. if sys.version[0] == '2':
  188. # Python 2
  189. return encode(text, encoding=encoding)
  190. else:
  191. # Python 3
  192. return decode(text, encoding=encoding)
  193. def parse_key_val(s, sep='=', dflt=None, val_type=None, vsep=None):
  194. """Parse a string into a dictionary, where entries are separated
  195. by newlines and the key and value are separated by `sep` (default: `=`)
  196. >>> parse_key_val('min=20\\nmax=50') == {'min': '20', 'max': '50'}
  197. True
  198. >>> parse_key_val('min=20\\nmax=50',
  199. ... val_type=float) == {'min': 20, 'max': 50}
  200. True
  201. :param str s: string to be parsed
  202. :param str sep: key/value separator
  203. :param dflt: default value to be used
  204. :param val_type: value type (None for no cast)
  205. :param vsep: vertical separator (default is Python 'universal newlines' approach)
  206. :return: parsed input (dictionary of keys/values)
  207. """
  208. result = KeyValue()
  209. if not s:
  210. return result
  211. if isinstance(s, bytes):
  212. sep = encode(sep)
  213. vsep = encode(vsep) if vsep else vsep
  214. if vsep:
  215. lines = s.split(vsep)
  216. try:
  217. lines.remove('\n')
  218. except ValueError:
  219. pass
  220. else:
  221. lines = s.splitlines()
  222. for line in lines:
  223. kv = line.split(sep, 1)
  224. k = decode(kv[0].strip())
  225. if len(kv) > 1:
  226. v = decode(kv[1].strip())
  227. else:
  228. v = dflt
  229. if val_type:
  230. result[k] = val_type(v)
  231. else:
  232. result[k] = v
  233. return result
  234. def get_num_suffix(number, max_number):
  235. """Returns formatted number with number of padding zeros
  236. depending on maximum number, used for creating suffix for data series.
  237. Does not include the suffix separator.
  238. :param number: number to be formatted as map suffix
  239. :param max_number: maximum number of the series to get number of digits
  240. >>> get_num_suffix(10, 1000)
  241. '0010'
  242. >>> get_num_suffix(10, 10)
  243. '10'
  244. """
  245. return '{number:0{width}d}'.format(width=len(str(max_number)),
  246. number=number)
  247. def split(s):
  248. """!Platform specific shlex.split"""
  249. if sys.version_info >= (2, 6):
  250. return shlex.split(s, posix = (sys.platform != "win32"))
  251. elif sys.platform == "win32":
  252. return shlex.split(s.replace('\\', r'\\'))
  253. else:
  254. return shlex.split(s)
  255. # source:
  256. # http://stackoverflow.com/questions/4836710/
  257. # does-python-have-a-built-in-function-for-string-natural-sort/4836734#4836734
  258. def natural_sort(l):
  259. """Returns sorted strings using natural sort
  260. """
  261. convert = lambda text: int(text) if text.isdigit() else text.lower()
  262. alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
  263. return sorted(l, key=alphanum_key)
  264. def get_lib_path(modname, libname=None):
  265. """Return the path of the libname contained in the module.
  266. """
  267. from os.path import isdir, join, sep
  268. from os import getenv
  269. if isdir(join(getenv('GISBASE'), 'etc', modname)):
  270. path = join(os.getenv('GISBASE'), 'etc', modname)
  271. elif getenv('GRASS_ADDON_BASE') and libname and \
  272. isdir(join(getenv('GRASS_ADDON_BASE'), 'etc', modname, libname)):
  273. path = join(getenv('GRASS_ADDON_BASE'), 'etc', modname)
  274. elif getenv('GRASS_ADDON_BASE') and \
  275. isdir(join(getenv('GRASS_ADDON_BASE'), 'etc', modname)):
  276. path = join(getenv('GRASS_ADDON_BASE'), 'etc', modname)
  277. elif getenv('GRASS_ADDON_BASE') and \
  278. isdir(join(getenv('GRASS_ADDON_BASE'), modname, modname)):
  279. path = join(os.getenv('GRASS_ADDON_BASE'), modname, modname)
  280. else:
  281. # used by g.extension compilation process
  282. cwd = os.getcwd()
  283. idx = cwd.find(modname)
  284. if idx < 0:
  285. return None
  286. path = '{cwd}{sep}etc{sep}{modname}'.format(cwd=cwd[:idx+len(modname)],
  287. sep=sep,
  288. modname=modname)
  289. if libname:
  290. path += '{pathsep}{cwd}{sep}etc{sep}{modname}{sep}{libname}'.format(
  291. cwd=cwd[:idx+len(modname)],
  292. sep=sep,
  293. modname=modname, libname=libname,
  294. pathsep=os.pathsep
  295. )
  296. return path
  297. def set_path(modulename, dirname=None, path='.'):
  298. """Set sys.path looking in the the local directory GRASS directories.
  299. :param modulename: string with the name of the GRASS module
  300. :param dirname: string with the directory name containing the python
  301. libraries, default None
  302. :param path: string with the path to reach the dirname locally.
  303. Example
  304. --------
  305. "set_path" example working locally with the source code of a module
  306. (r.green) calling the function with all the parameters. Below it is
  307. reported the directory structure on the r.green module.
  308. ::
  309. grass_prompt> pwd
  310. ~/Download/r.green/r.green.hydro/r.green.hydro.financial
  311. grass_prompt> tree ../../../r.green
  312. ../../../r.green
  313. |-- ...
  314. |-- libgreen
  315. | |-- pyfile1.py
  316. | +-- pyfile2.py
  317. +-- r.green.hydro
  318. |-- Makefile
  319. |-- libhydro
  320. | |-- pyfile1.py
  321. | +-- pyfile2.py
  322. |-- r.green.hydro.*
  323. +-- r.green.hydro.financial
  324. |-- Makefile
  325. |-- ...
  326. +-- r.green.hydro.financial.py
  327. 21 directories, 125 files
  328. in the source code the function is called with the following parameters: ::
  329. set_path('r.green', 'libhydro', '..')
  330. set_path('r.green', 'libgreen', os.path.join('..', '..'))
  331. when we are executing the module: r.green.hydro.financial locally from
  332. the command line: ::
  333. grass_prompt> python r.green.hydro.financial.py --ui
  334. In this way we are executing the local code even if the module was already
  335. installed as grass-addons and it is available in GRASS standards path.
  336. The function is cheching if the dirname is provided and if the
  337. directory exists and it is available using the path
  338. provided as third parameter, if yes add the path to sys.path to be
  339. importable, otherwise it will check on GRASS GIS standard paths.
  340. """
  341. import sys
  342. # TODO: why dirname is checked first - the logic should be revised
  343. pathlib = None
  344. if dirname:
  345. pathlib = os.path.join(path, dirname)
  346. if pathlib and os.path.exists(pathlib):
  347. # we are running the script from the script directory, therefore
  348. # we add the path to sys.path to reach the directory (dirname)
  349. sys.path.append(os.path.abspath(path))
  350. else:
  351. # running from GRASS GIS session
  352. path = get_lib_path(modulename, dirname)
  353. if path is None:
  354. pathname = os.path.join(modulename, dirname) if dirname else modulename
  355. raise ImportError("Not able to find the path '%s' directory "
  356. "(current dir '%s')." % (pathname, os.getcwd()))
  357. sys.path.insert(0, path)