utils.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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. import time
  22. import platform
  23. import uuid
  24. import random
  25. import string
  26. if sys.version_info.major >= 3:
  27. unicode = str
  28. def float_or_dms(s):
  29. """Convert DMS to float.
  30. >>> round(float_or_dms('26:45:30'), 5)
  31. 26.75833
  32. >>> round(float_or_dms('26:0:0.1'), 5)
  33. 26.00003
  34. :param s: DMS value
  35. :return: float value
  36. """
  37. if s[-1] in ["E", "W", "N", "S"]:
  38. s = s[:-1]
  39. return sum(float(x) / 60 ** n for (n, x) in enumerate(s.split(":")))
  40. def separator(sep):
  41. """Returns separator from G_OPT_F_SEP appropriately converted
  42. to character.
  43. >>> separator('pipe')
  44. '|'
  45. >>> separator('comma')
  46. ','
  47. If the string does not match any of the separator keywords,
  48. it is returned as is:
  49. >>> separator(', ')
  50. ', '
  51. :param str separator: character or separator keyword
  52. :return: separator character
  53. """
  54. if sep == "pipe":
  55. return "|"
  56. elif sep == "comma":
  57. return ","
  58. elif sep == "space":
  59. return " "
  60. elif sep == "tab" or sep == "\\t":
  61. return "\t"
  62. elif sep == "newline" or sep == "\\n":
  63. return "\n"
  64. return sep
  65. def diff_files(filename_a, filename_b):
  66. """Diffs two text files and returns difference.
  67. :param str filename_a: first file path
  68. :param str filename_b: second file path
  69. :return: list of strings
  70. """
  71. import difflib
  72. differ = difflib.Differ()
  73. fh_a = open(filename_a, "r")
  74. fh_b = open(filename_b, "r")
  75. result = list(differ.compare(fh_a.readlines(), fh_b.readlines()))
  76. return result
  77. def try_remove(path):
  78. """Attempt to remove a file; no exception is generated if the
  79. attempt fails.
  80. :param str path: path to file to remove
  81. """
  82. try:
  83. os.remove(path)
  84. except:
  85. pass
  86. def try_rmdir(path):
  87. """Attempt to remove a directory; no exception is generated if the
  88. attempt fails.
  89. :param str path: path to directory to remove
  90. """
  91. try:
  92. os.rmdir(path)
  93. except:
  94. shutil.rmtree(path, ignore_errors=True)
  95. def basename(path, ext=None):
  96. """Remove leading directory components and an optional extension
  97. from the specified path
  98. :param str path: path
  99. :param str ext: extension
  100. """
  101. name = os.path.basename(path)
  102. if not ext:
  103. return name
  104. fs = name.rsplit(".", 1)
  105. if len(fs) > 1 and fs[1].lower() == ext:
  106. name = fs[0]
  107. return name
  108. class KeyValue(dict):
  109. """A general-purpose key-value store.
  110. KeyValue is a subclass of dict, but also allows entries to be read and
  111. written using attribute syntax. Example:
  112. >>> reg = KeyValue()
  113. >>> reg['north'] = 489
  114. >>> reg.north
  115. 489
  116. >>> reg.south = 205
  117. >>> reg['south']
  118. 205
  119. """
  120. def __getattr__(self, key):
  121. return self[key]
  122. def __setattr__(self, key, value):
  123. self[key] = value
  124. def _get_encoding():
  125. encoding = locale.getdefaultlocale()[1]
  126. if not encoding:
  127. encoding = "UTF-8"
  128. return encoding
  129. def decode(bytes_, encoding=None):
  130. """Decode bytes with default locale and return (unicode) string
  131. No-op if parameter is not bytes (assumed unicode string).
  132. :param bytes bytes_: the bytes to decode
  133. :param encoding: encoding to be used, default value is None
  134. Example
  135. -------
  136. >>> decode(b'S\xc3\xbcdtirol')
  137. u'Südtirol'
  138. >>> decode(u'Südtirol')
  139. u'Südtirol'
  140. >>> decode(1234)
  141. u'1234'
  142. """
  143. if isinstance(bytes_, unicode):
  144. return bytes_
  145. if isinstance(bytes_, bytes):
  146. if encoding is None:
  147. enc = _get_encoding()
  148. else:
  149. enc = encoding
  150. return bytes_.decode(enc)
  151. # if something else than text
  152. if sys.version_info.major >= 3:
  153. # only text should be used
  154. raise TypeError("can only accept types str and bytes")
  155. else:
  156. # for backwards compatibility
  157. return unicode(bytes_)
  158. def encode(string, encoding=None):
  159. """Encode string with default locale and return bytes with that encoding
  160. No-op if parameter is bytes (assumed already encoded).
  161. This ensures garbage in, garbage out.
  162. :param str string: the string to encode
  163. :param encoding: encoding to be used, default value is None
  164. Example
  165. -------
  166. >>> encode(b'S\xc3\xbcdtirol')
  167. b'S\xc3\xbcdtirol'
  168. >>> decode(u'Südtirol')
  169. b'S\xc3\xbcdtirol'
  170. >>> decode(1234)
  171. b'1234'
  172. """
  173. if isinstance(string, bytes):
  174. return string
  175. # this also tests str in Py3:
  176. if isinstance(string, unicode):
  177. if encoding is None:
  178. enc = _get_encoding()
  179. else:
  180. enc = encoding
  181. return string.encode(enc)
  182. # if something else than text
  183. if sys.version_info.major >= 3:
  184. # only text should be used
  185. raise TypeError("can only accept types str and bytes")
  186. else:
  187. # for backwards compatibility
  188. return bytes(string)
  189. def text_to_string(text, encoding=None):
  190. """Convert text to str. Useful when passing text into environments,
  191. in Python 2 it needs to be bytes on Windows, in Python 3 in needs unicode.
  192. """
  193. if sys.version[0] == "2":
  194. # Python 2
  195. return encode(text, encoding=encoding)
  196. else:
  197. # Python 3
  198. return decode(text, encoding=encoding)
  199. def parse_key_val(s, sep="=", dflt=None, val_type=None, vsep=None):
  200. """Parse a string into a dictionary, where entries are separated
  201. by newlines and the key and value are separated by `sep` (default: `=`)
  202. >>> parse_key_val('min=20\\nmax=50') == {'min': '20', 'max': '50'}
  203. True
  204. >>> parse_key_val('min=20\\nmax=50',
  205. ... val_type=float) == {'min': 20, 'max': 50}
  206. True
  207. :param str s: string to be parsed
  208. :param str sep: key/value separator
  209. :param dflt: default value to be used
  210. :param val_type: value type (None for no cast)
  211. :param vsep: vertical separator (default is Python 'universal newlines' approach)
  212. :return: parsed input (dictionary of keys/values)
  213. """
  214. result = KeyValue()
  215. if not s:
  216. return result
  217. if isinstance(s, bytes):
  218. sep = encode(sep)
  219. vsep = encode(vsep) if vsep else vsep
  220. if vsep:
  221. lines = s.split(vsep)
  222. try:
  223. lines.remove("\n")
  224. except ValueError:
  225. pass
  226. else:
  227. lines = s.splitlines()
  228. for line in lines:
  229. kv = line.split(sep, 1)
  230. k = decode(kv[0].strip())
  231. if len(kv) > 1:
  232. v = decode(kv[1].strip())
  233. else:
  234. v = dflt
  235. if val_type:
  236. result[k] = val_type(v)
  237. else:
  238. result[k] = v
  239. return result
  240. def get_num_suffix(number, max_number):
  241. """Returns formatted number with number of padding zeros
  242. depending on maximum number, used for creating suffix for data series.
  243. Does not include the suffix separator.
  244. :param number: number to be formatted as map suffix
  245. :param max_number: maximum number of the series to get number of digits
  246. >>> get_num_suffix(10, 1000)
  247. '0010'
  248. >>> get_num_suffix(10, 10)
  249. '10'
  250. """
  251. return "{number:0{width}d}".format(width=len(str(max_number)), number=number)
  252. def split(s):
  253. """!Platform specific shlex.split"""
  254. if sys.version_info >= (2, 6):
  255. return shlex.split(s, posix=(sys.platform != "win32"))
  256. elif sys.platform == "win32":
  257. return shlex.split(s.replace("\\", r"\\"))
  258. else:
  259. return shlex.split(s)
  260. # source:
  261. # http://stackoverflow.com/questions/4836710/
  262. # does-python-have-a-built-in-function-for-string-natural-sort/4836734#4836734
  263. def natural_sort(l):
  264. """Returns sorted list using natural sort
  265. (deprecated, use naturally_sorted)
  266. """
  267. return naturally_sorted(l)
  268. def naturally_sorted(l, key=None):
  269. """Returns sorted list using natural sort"""
  270. copy_l = l[:]
  271. naturally_sort(copy_l, key)
  272. return copy_l
  273. def naturally_sort(l, key=None):
  274. """Sorts lists using natural sort"""
  275. def convert(text):
  276. return int(text) if text.isdigit() else text.lower()
  277. def alphanum_key(actual_key):
  278. if key:
  279. sort_key = key(actual_key)
  280. else:
  281. sort_key = actual_key
  282. return [convert(c) for c in re.split("([0-9]+)", sort_key)]
  283. l.sort(key=alphanum_key)
  284. def get_lib_path(modname, libname=None):
  285. """Return the path of the libname contained in the module."""
  286. from os.path import isdir, join, sep
  287. from os import getenv
  288. if isdir(join(getenv("GISBASE"), "etc", modname)):
  289. path = join(os.getenv("GISBASE"), "etc", modname)
  290. elif (
  291. getenv("GRASS_ADDON_BASE")
  292. and libname
  293. and isdir(join(getenv("GRASS_ADDON_BASE"), "etc", modname, libname))
  294. ):
  295. path = join(getenv("GRASS_ADDON_BASE"), "etc", modname)
  296. elif getenv("GRASS_ADDON_BASE") and isdir(
  297. join(getenv("GRASS_ADDON_BASE"), "etc", modname)
  298. ):
  299. path = join(getenv("GRASS_ADDON_BASE"), "etc", modname)
  300. elif getenv("GRASS_ADDON_BASE") and isdir(
  301. join(getenv("GRASS_ADDON_BASE"), modname, modname)
  302. ):
  303. path = join(os.getenv("GRASS_ADDON_BASE"), modname, modname)
  304. else:
  305. # used by g.extension compilation process
  306. cwd = os.getcwd()
  307. idx = cwd.find(modname)
  308. if idx < 0:
  309. return None
  310. path = "{cwd}{sep}etc{sep}{modname}".format(
  311. cwd=cwd[: idx + len(modname)], sep=sep, modname=modname
  312. )
  313. if libname:
  314. path += "{pathsep}{cwd}{sep}etc{sep}{modname}{sep}{libname}".format(
  315. cwd=cwd[: idx + len(modname)],
  316. sep=sep,
  317. modname=modname,
  318. libname=libname,
  319. pathsep=os.pathsep,
  320. )
  321. return path
  322. def set_path(modulename, dirname=None, path="."):
  323. """Set sys.path looking in the the local directory GRASS directories.
  324. :param modulename: string with the name of the GRASS module
  325. :param dirname: string with the directory name containing the python
  326. libraries, default None
  327. :param path: string with the path to reach the dirname locally.
  328. Example
  329. --------
  330. "set_path" example working locally with the source code of a module
  331. (r.green) calling the function with all the parameters. Below it is
  332. reported the directory structure on the r.green module.
  333. ::
  334. grass_prompt> pwd
  335. ~/Download/r.green/r.green.hydro/r.green.hydro.financial
  336. grass_prompt> tree ../../../r.green
  337. ../../../r.green
  338. |-- ...
  339. |-- libgreen
  340. | |-- pyfile1.py
  341. | +-- pyfile2.py
  342. +-- r.green.hydro
  343. |-- Makefile
  344. |-- libhydro
  345. | |-- pyfile1.py
  346. | +-- pyfile2.py
  347. |-- r.green.hydro.*
  348. +-- r.green.hydro.financial
  349. |-- Makefile
  350. |-- ...
  351. +-- r.green.hydro.financial.py
  352. 21 directories, 125 files
  353. in the source code the function is called with the following parameters: ::
  354. set_path('r.green', 'libhydro', '..')
  355. set_path('r.green', 'libgreen', os.path.join('..', '..'))
  356. when we are executing the module: r.green.hydro.financial locally from
  357. the command line: ::
  358. grass_prompt> python r.green.hydro.financial.py --ui
  359. In this way we are executing the local code even if the module was already
  360. installed as grass-addons and it is available in GRASS standards path.
  361. The function is cheching if the dirname is provided and if the
  362. directory exists and it is available using the path
  363. provided as third parameter, if yes add the path to sys.path to be
  364. importable, otherwise it will check on GRASS GIS standard paths.
  365. """
  366. import sys
  367. # TODO: why dirname is checked first - the logic should be revised
  368. pathlib = None
  369. if dirname:
  370. pathlib = os.path.join(path, dirname)
  371. if pathlib and os.path.exists(pathlib):
  372. # we are running the script from the script directory, therefore
  373. # we add the path to sys.path to reach the directory (dirname)
  374. sys.path.append(os.path.abspath(path))
  375. else:
  376. # running from GRASS GIS session
  377. path = get_lib_path(modulename, dirname)
  378. if path is None:
  379. pathname = os.path.join(modulename, dirname) if dirname else modulename
  380. raise ImportError(
  381. "Not able to find the path '%s' directory "
  382. "(current dir '%s')." % (pathname, os.getcwd())
  383. )
  384. sys.path.insert(0, path)
  385. def clock():
  386. """
  387. Return time counter to measure performance for chunks of code.
  388. Uses time.clock() for Py < 3.3, time.perf_counter() for Py >= 3.3.
  389. Should be used only as difference between the calls.
  390. """
  391. if sys.version_info > (3, 2):
  392. return time.perf_counter()
  393. return time.clock()
  394. def legalize_vector_name(name, fallback_prefix="x"):
  395. """Make *name* usable for vectors, tables, and columns
  396. The returned string is a name usable for vectors, tables, and columns,
  397. i.e., it is a vector legal name which is a string containing only
  398. lowercase and uppercase ASCII letters, digits, and underscores.
  399. Invalid characters are replaced by underscores.
  400. If the name starts with an invalid character, the name is prefixed with
  401. *fallback_prefix*. This increases the length of the resulting name by the
  402. length of the prefix.
  403. The *fallback_prefix* can be empty which is useful when the *name* is later
  404. used as a suffix for some other valid name.
  405. ValueError is raised when provided *name* is empty or *fallback_prefix*
  406. does not start with a valid character.
  407. """
  408. # The implementation is based on Vect_legal_filename().
  409. if not name:
  410. raise ValueError("name cannot be empty")
  411. if fallback_prefix and re.match("[^A-Za-z]", fallback_prefix[0]):
  412. raise ValueError("fallback_prefix must start with an ASCII letter")
  413. if fallback_prefix and re.match("[^A-Za-z]", name[0], flags=re.ASCII):
  414. # We prefix here rather than just replace, because in cases of unique
  415. # identifiers, e.g., columns or node names, replacing the first
  416. # character by the same replacement character increases chances of
  417. # conflict (e.g. column names 10, 20, 30).
  418. name = "{fallback_prefix}{name}".format(**locals())
  419. name = re.sub("[^A-Za-z0-9_]", "_", name, flags=re.ASCII)
  420. keywords = ["and", "or", "not"]
  421. if name in keywords:
  422. name = "{name}_".format(**locals())
  423. return name
  424. def append_node_pid(name):
  425. """Add node name and PID to a name (string)
  426. For the result to be unique, the name needs to be unique within a process.
  427. Given that, the result will be unique enough for use in temporary maps
  428. and other elements on single machine or an HPC cluster.
  429. The returned string is a name usable for vectors, tables, and columns
  430. (vector legal name) as long as provided argument *name* is.
  431. >>> append_node_pid("tmp_raster_1")
  432. ..note::
  433. Before you use this function for creating temporary files (i.e., normal
  434. files on disk, not maps and other mapset elements), see functions
  435. designed for it in the GRASS GIS or standard Python library. These
  436. take care of collisions already on different levels.
  437. """
  438. # We are using this node as a suffix, so we don't need to make sure it
  439. # is prefixed with additional character(s) since that's exactly what
  440. # happens in this function.
  441. # Note that this may still cause collisions when nodes are named in a way
  442. # that they collapse into the same name after the replacements are done,
  443. # but we consider that unlikely given that
  444. # nodes will be likely already named as something close to what we need.
  445. node = legalize_vector_name(platform.node(), fallback_prefix="")
  446. pid = os.getpid()
  447. return "{name}_{node}_{pid}".format(**locals())
  448. def append_uuid(name):
  449. """Add UUID4 to a name (string)
  450. To generate a name of an temporary mapset element which is unique in a
  451. system, use :func:`append_node_pid()` in a combination with a name unique
  452. within your process.
  453. To avoid collisions, never shorten the name obtained from this function.
  454. A shortened UUID does not have the collision guarantees the full UUID has.
  455. For a random name of a given shorter size, see :func:`append_random()`.
  456. >>> append_uuid("tmp")
  457. ..note::
  458. See the note about creating temporary files in the
  459. :func:`append_node_pid()` description.
  460. """
  461. suffix = uuid.uuid4().hex
  462. return "{name}_{suffix}".format(**locals())
  463. def append_random(name, suffix_length=None, total_length=None):
  464. """Add a random part to of a specified length to a name (string)
  465. >>> append_random("tmp", 8)
  466. >>> append_random("tmp", total_length=16)
  467. ..note::
  468. Note that this will be influeced by the random seed set for the Python
  469. random package.
  470. ..note::
  471. See the note about creating temporary files in the
  472. :func:`append_node_pid()` description.
  473. """
  474. if suffix_length and total_length:
  475. raise ValueError(
  476. "Either suffix_length or total_length can be provided, not both"
  477. )
  478. if not suffix_length and not total_length:
  479. raise ValueError("suffix_length or total_length has to be provided")
  480. if total_length:
  481. # remove len of name and one underscore
  482. name_length = len(name)
  483. suffix_length = total_length - name_length - 1
  484. if suffix_length <= 0:
  485. raise ValueError(
  486. "No characters left for the suffix:"
  487. " total_length <{total_length}> is too small"
  488. " or name <{name}> ({name_length}) is too long".format(**locals())
  489. )
  490. # We don't do lower and upper case because that could cause conflicts in
  491. # contexts which are case-insensitive.
  492. # We use lowercase because that's what is in UUID4 hex string.
  493. allowed_chars = string.ascii_lowercase + string.digits
  494. # The following can be shorter with random.choices from Python 3.6.
  495. suffix = "".join(random.choice(allowed_chars) for _ in range(suffix_length))
  496. return "{name}_{suffix}".format(**locals())