utils.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. """
  2. @package startup.utils
  3. @brief General GUI-independent utilities for GUI startup of GRASS GIS
  4. (C) 2017-2018 by Vaclav Petras the GRASS Development Team
  5. This program is free software under the GNU General Public License
  6. (>=v2). Read the file COPYING that comes with GRASS for details.
  7. @author Vaclav Petras <wenzeslaus gmail com>
  8. This file should not use (import) anything from GUI code (wx or wxGUI).
  9. This can potentially be part of the Python library (i.e. it needs to
  10. solve the errors etc. in a general manner).
  11. """
  12. import os
  13. import tempfile
  14. import getpass
  15. import sys
  16. def get_possible_database_path():
  17. """Looks for directory 'grassdata' (case-insensitive) in standard
  18. locations to detect existing GRASS Database.
  19. Returns the path as a string or None if nothing was found.
  20. """
  21. home = os.path.expanduser("~")
  22. # try some common directories for grassdata
  23. candidates = [
  24. home,
  25. os.path.join(home, "Documents"),
  26. ]
  27. # find possible database path
  28. for candidate in candidates:
  29. if os.path.exists(candidate):
  30. for subdir in next(os.walk(candidate))[1]:
  31. if "grassdata" in subdir.lower():
  32. return os.path.join(candidate, subdir)
  33. return None
  34. def create_database_directory():
  35. """Creates the standard GRASS GIS directory.
  36. Creates database directory named grassdata in the standard location
  37. according to the platform.
  38. Returns the new path as a string or None if nothing was found or created.
  39. """
  40. home = os.path.expanduser("~")
  41. # Determine the standard path according to the platform
  42. if sys.platform == "win32":
  43. path = os.path.join(home, "Documents", "grassdata")
  44. else:
  45. path = os.path.join(home, "grassdata")
  46. # Create "grassdata" directory
  47. try:
  48. os.mkdir(path)
  49. return path
  50. except OSError:
  51. pass
  52. # Create a temporary "grassdata" directory if GRASS is running
  53. # in some special environment and the standard directories
  54. # cannot be created which might be the case in some "try out GRASS"
  55. # use cases.
  56. path = os.path.join(tempfile.gettempdir(), "grassdata_{}".format(getpass.getuser()))
  57. # The created tmp is not cleaned by GRASS, so we are relying on
  58. # the system to do it at some point. The positive outcome is that
  59. # another GRASS instance will find the data created by the first
  60. # one which is desired in the "try out GRASS" use case we are
  61. # aiming towards."
  62. if os.path.exists(path):
  63. return path
  64. try:
  65. os.mkdir(path)
  66. return path
  67. except OSError:
  68. pass
  69. return None