grass.py 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201
  1. #!/usr/bin/env python
  2. #############################################################################
  3. #
  4. # MODULE: GRASS initialization script
  5. # AUTHOR(S): Original author unknown - probably CERL
  6. # Andreas Lange <andreas.lange rhein-main.de>
  7. # Huidae Cho <grass4u gmail.com>
  8. # Justin Hickey <jhickey hpcc.nectec.or.th>
  9. # Markus Neteler <neteler osgeo.org>
  10. # Hamish Bowman <hamish_b yahoo.com>
  11. #
  12. # GRASS 7: converted to Python (based on init.sh shell
  13. # script from GRASS 6) by Glynn Clements
  14. # Martin Landa <landa.martin gmail.com>
  15. # Luca Delucchi <lucadeluge gmail.com>
  16. # Vaclav Petras <wenzeslaus gmail.com> (refactoring and exec)
  17. # PURPOSE: Sets up environment variables, parses any remaining
  18. # command line options for setting the GISDBASE, LOCATION,
  19. # and/or MAPSET. Finally it starts GRASS with the appropriate
  20. # user interface and cleans up after it is finished.
  21. # COPYRIGHT: (C) 2000-2019 by the GRASS Development Team
  22. #
  23. # This program is free software under the GNU General
  24. # Public License (>=v2). Read the file COPYING that
  25. # comes with GRASS for details.
  26. #
  27. #############################################################################
  28. """
  29. Script to run GRASS session.
  30. Some of the functions could be used separately but import from this module
  31. is not safe, i.e. it has side effects (this should be changed in the future).
  32. """
  33. # we allow for long file because we want to avoid imports if possible
  34. # (this makes it more stable since we have to set up paths first)
  35. # pylint: disable=too-many-lines
  36. from __future__ import print_function
  37. import sys
  38. import os
  39. import errno
  40. import atexit
  41. import gettext
  42. import shutil
  43. import signal
  44. import string
  45. import subprocess
  46. import types
  47. import re
  48. import six
  49. import platform
  50. import tempfile
  51. import locale
  52. # mechanism meant for debugging this script (only)
  53. # private global to store if we are debugging
  54. _DEBUG = None
  55. # for wxpath
  56. _WXPYTHON_BASE = None
  57. ENCODING = locale.getdefaultlocale()[1]
  58. if ENCODING is None:
  59. ENCODING = 'UTF-8'
  60. print("Default locale not found, using UTF-8") # intentionally not translatable
  61. # The "@...@" variables are being substituted during build process
  62. #
  63. # TODO: should GISBASE be renamed to something like GRASS_PATH?
  64. # GISBASE marks complete runtime, so no need to get it here when
  65. # setting it up, possible scenario: existing runtime and starting
  66. # GRASS in that, we want to overwrite the settings, not to take it
  67. # possibly same for GRASS_PROJSHARE and others but maybe not
  68. #
  69. # We need to simultaneously make sure that:
  70. # - we get GISBASE from os.environ if it is defined (doesn't this mean that we are already
  71. # inside a GRASS session? If we are, why do we need to run this script again???).
  72. # - GISBASE exists as an ENV variable
  73. #
  74. # pmav99: Ugly as hell, but that's what the code before the refactoring was doing.
  75. if 'GISBASE' in os.environ and len(os.getenv('GISBASE')) > 0:
  76. GISBASE = os.path.normpath(os.environ["GISBASE"])
  77. else:
  78. GISBASE = os.path.normpath("@GISBASE@")
  79. os.environ['GISBASE'] = GISBASE
  80. CMD_NAME = "@START_UP@"
  81. GRASS_VERSION = "@GRASS_VERSION_NUMBER@"
  82. LD_LIBRARY_PATH_VAR = '@LD_LIBRARY_PATH_VAR@'
  83. CONFIG_PROJSHARE = os.environ.get('GRASS_PROJSHARE', "@CONFIG_PROJSHARE@")
  84. # Get the system name
  85. WINDOWS = sys.platform == 'win32'
  86. CYGWIN = "cygwin" in sys.platform
  87. MACOSX = "darwin" in sys.platform
  88. def decode(bytes_, encoding=ENCODING):
  89. """Decode bytes with default locale and return (unicode) string
  90. Adapted from lib/python/core/utils.py
  91. No-op if parameter is not bytes (assumed unicode string).
  92. :param bytes bytes_: the bytes to decode
  93. :param encoding: encoding to be used, default value is the system's default
  94. encoding or, if that cannot be determined, 'UTF-8'.
  95. """
  96. if sys.version_info.major >= 3:
  97. unicode = str
  98. if isinstance(bytes_, unicode):
  99. return bytes_
  100. elif isinstance(bytes_, bytes):
  101. return bytes_.decode(encoding)
  102. else:
  103. # if something else than text
  104. raise TypeError("can only accept types str and bytes")
  105. def encode(string, encoding=ENCODING):
  106. """Encode string with default locale and return bytes with that encoding
  107. Adapted from lib/python/core/utils.py
  108. No-op if parameter is bytes (assumed already encoded).
  109. This ensures garbage in, garbage out.
  110. :param str string: the string to encode
  111. :param encoding: encoding to be used, default value is the system's default
  112. encoding or, if that cannot be determined, 'UTF-8'.
  113. """
  114. if sys.version_info.major >= 3:
  115. unicode = str
  116. if isinstance(string, bytes):
  117. return string
  118. # this also tests str in Py3:
  119. elif isinstance(string, unicode):
  120. return string.encode(encoding)
  121. else:
  122. # if something else than text
  123. raise TypeError("can only accept types str and bytes")
  124. # see https://trac.osgeo.org/grass/ticket/3508
  125. def to_text_string(obj, encoding=ENCODING):
  126. """Convert `obj` to (unicode) text string"""
  127. if six.PY2:
  128. # Python 2
  129. return encode(obj, encoding=encoding)
  130. else:
  131. # Python 3
  132. return decode(obj, encoding=encoding)
  133. def try_remove(path):
  134. try:
  135. os.remove(path)
  136. except:
  137. pass
  138. def clean_env():
  139. gisrc = os.environ['GISRC']
  140. env_curr = read_gisrc(gisrc)
  141. env_new = {}
  142. for k, v in env_curr.items():
  143. if k.endswith('PID') or k.startswith('MONITOR'):
  144. continue
  145. env_new[k] = v
  146. write_gisrc(env_new, gisrc)
  147. def is_debug():
  148. """Returns True if we are in debug mode
  149. For debug messages use ``debug()``.
  150. """
  151. global _DEBUG
  152. if _DEBUG is not None:
  153. return _DEBUG
  154. _DEBUG = os.getenv('GRASS_DEBUG')
  155. # translate to bool (no or empty variable means false)
  156. if _DEBUG:
  157. _DEBUG = True
  158. else:
  159. _DEBUG = False
  160. return _DEBUG
  161. def debug(msg):
  162. """Print a debug message if in debug mode
  163. Do not use translatable strings for debug messages.
  164. """
  165. if is_debug():
  166. sys.stderr.write("DEBUG: %s\n" % msg)
  167. sys.stderr.flush()
  168. def message(msg):
  169. sys.stderr.write(msg + "\n")
  170. sys.stderr.flush()
  171. def warning(text):
  172. sys.stderr.write(_("WARNING") + ': ' + text + os.linesep)
  173. def fatal(msg):
  174. sys.stderr.write("%s: " % _('ERROR') + msg + os.linesep)
  175. sys.exit(_("Exiting..."))
  176. def readfile(path):
  177. debug("Reading %s" % path)
  178. f = open(path, 'r')
  179. s = f.read()
  180. f.close()
  181. return s
  182. def writefile(path, s):
  183. debug("Writing %s" % path)
  184. f = open(path, 'w')
  185. f.write(s)
  186. f.close()
  187. def call(cmd, **kwargs):
  188. """Wrapper for subprocess.call to deal with platform-specific issues"""
  189. if WINDOWS:
  190. kwargs['shell'] = True
  191. return subprocess.call(cmd, **kwargs)
  192. def Popen(cmd, **kwargs): # pylint: disable=C0103
  193. """Wrapper for subprocess.Popen to deal with platform-specific issues"""
  194. if WINDOWS:
  195. kwargs['shell'] = True
  196. return subprocess.Popen(cmd, **kwargs)
  197. def gpath(*args):
  198. """Costruct path to file or directory in GRASS GIS installation
  199. Can be called only after GISBASE was set.
  200. """
  201. return os.path.join(GISBASE, *args)
  202. def wxpath(*args):
  203. """Costruct path to file or directory in GRASS wxGUI
  204. Can be called only after GISBASE was set.
  205. This function does not check if the directories exist or if GUI works
  206. this must be done by the caller if needed.
  207. """
  208. global _WXPYTHON_BASE
  209. if not _WXPYTHON_BASE:
  210. # this can be called only after GISBASE was set
  211. _WXPYTHON_BASE = gpath("gui", "wxpython")
  212. return os.path.join(_WXPYTHON_BASE, *args)
  213. # using format for most but leaving usage of template for the dynamic ones
  214. # two different methods are easy way to implement two phase construction
  215. HELP_TEXT = r"""GRASS GIS $VERSION_NUMBER
  216. Geographic Resources Analysis Support System (GRASS GIS).
  217. {usage}:
  218. $CMD_NAME [-h | --help] [-v | --version]
  219. [-c | -c geofile | -c EPSG:code[:datum_trans] | -c XY]
  220. [-e] [-f] [--text | --gtext | --gui] [--config param]
  221. [[[GISDBASE/]LOCATION/]MAPSET]
  222. $CMD_NAME [FLAG]... GISDBASE/LOCATION/MAPSET --exec EXECUTABLE [EPARAM]...
  223. $CMD_NAME --tmp-location [geofile | EPSG | XY] --exec EXECUTABLE [EPARAM]...
  224. {flags}:
  225. -h or --help {help_flag}
  226. -v or --version {version_flag}
  227. -c {create}
  228. -e {exit_after}
  229. -f {force_removal}
  230. --text {text}
  231. {text_detail}
  232. --gtext {gtext}
  233. {gtext_detail}
  234. --gui {gui}
  235. {gui_detail}
  236. --config {config}
  237. {config_detail}
  238. --exec EXECUTABLE {exec_}
  239. {exec_detail}
  240. --tmp-location {tmp_location}
  241. {params}:
  242. GISDBASE {gisdbase}
  243. {gisdbase_detail}
  244. LOCATION {location}
  245. {location_detail}
  246. MAPSET {mapset}
  247. GISDBASE/LOCATION/MAPSET {full_mapset}
  248. EXECUTABLE {executable}
  249. EPARAM {executable_params}
  250. FLAG {standard_flags}
  251. {env_vars}:
  252. GRASS_GUI {gui_var}
  253. GRASS_HTML_BROWSER {html_var}
  254. GRASS_ADDON_PATH {addon_path_var}
  255. GRASS_ADDON_BASE {addon_base_var}
  256. GRASS_BATCH_JOB {batch_var}
  257. GRASS_PYTHON {python_var}
  258. """
  259. def help_message(default_gui):
  260. t = string.Template(
  261. HELP_TEXT.format(
  262. usage=_("Usage"),
  263. flags=_("Flags"),
  264. help_flag=_("print this help message"),
  265. version_flag=_("show version information and exit"),
  266. create=_("create given database, location or mapset if it doesn't exist"),
  267. exit_after=_("exit after creation of location or mapset. Only with -c flag"),
  268. force_removal=_("force removal of .gislock if exists (use with care!). Only with --text flag"),
  269. text=_("use text based interface (skip graphical welcome screen)"),
  270. text_detail=_("and set as default"),
  271. gtext=_("use text based interface (show graphical welcome screen)"),
  272. gtext_detail=_("and set as default"),
  273. gui=_("use $DEFAULT_GUI graphical user interface"),
  274. gui_detail=_("and set as default"),
  275. config=_("print GRASS configuration parameters"),
  276. config_detail=_("options: arch,build,compiler,path,revision,svn_revision,version"),
  277. params=_("Parameters"),
  278. gisdbase=_("initial GRASS database directory"),
  279. gisdbase_detail=_("directory containing Locations"),
  280. location=_("initial GRASS Location"),
  281. location_detail=_("directory containing Mapsets with one common coordinate system (projection)"),
  282. mapset=_("initial GRASS Mapset"),
  283. full_mapset=_("fully qualified initial Mapset directory"),
  284. env_vars=_("Environment variables relevant for startup"),
  285. gui_var=_("select GUI (text, gui, gtext)"),
  286. html_var=_("set html web browser for help pages"),
  287. addon_path_var=_("set additional path(s) to local GRASS modules or user scripts"),
  288. addon_base_var=_("set additional GISBASE for locally installed GRASS Addons"),
  289. batch_var=_("shell script to be processed as batch job"),
  290. python_var=_("set Python interpreter name to override 'python'"),
  291. exec_=_("execute GRASS module or script"),
  292. exec_detail=_("provided executable will be executed in GRASS session"),
  293. executable=_("GRASS module, script or any other executable"),
  294. executable_params=_("parameters of the executable"),
  295. standard_flags=_("standard flags"),
  296. tmp_location=_("create temporary location (use with the --exec flag)"),
  297. )
  298. )
  299. s = t.substitute(CMD_NAME=CMD_NAME, DEFAULT_GUI=default_gui,
  300. VERSION_NUMBER=GRASS_VERSION)
  301. sys.stderr.write(s)
  302. def get_grass_config_dir():
  303. """Get configuration directory
  304. Determines path of GRASS GIS user configuration directory and creates
  305. it if it does not exist.
  306. Configuration directory is for example used for grass env file
  307. (the one which caries mapset settings from session to session).
  308. """
  309. if sys.platform == 'win32':
  310. grass_config_dirname = "GRASS7"
  311. win_conf_path = os.getenv('APPDATA')
  312. # this can happen with some strange settings
  313. if not win_conf_path:
  314. fatal(_("The APPDATA variable is not set, ask your operating"
  315. " system support"))
  316. if not os.path.exists(win_conf_path):
  317. fatal(_("The APPDATA variable points to directory which does"
  318. " not exist, ask your operating system support"))
  319. directory = os.path.join(win_conf_path, grass_config_dirname)
  320. else:
  321. grass_config_dirname = ".grass7"
  322. directory = os.path.join(os.getenv('HOME'), grass_config_dirname)
  323. if not os.path.isdir(directory) :
  324. try:
  325. os.mkdir(directory)
  326. except OSError as e:
  327. # Can happen as a race condition
  328. if not e.errno == errno.EEXIST or not os.path.isdir(directory):
  329. fatal(
  330. _("Failed to create configuration directory '%s' with error: %s")
  331. % (directory, e.strerror))
  332. return directory
  333. def create_tmp(user, gis_lock):
  334. """Create temporary directory
  335. :param user: user name to be used in the directory name
  336. :param gis_lock: session lock filename to be used in the directory name
  337. """
  338. # use $TMPDIR if it exists, then $TEMP, otherwise /tmp
  339. tmp = os.getenv('TMPDIR')
  340. if not tmp:
  341. tmp = os.getenv('TEMP')
  342. if not tmp:
  343. tmp = os.getenv('TMP')
  344. if not tmp:
  345. tmp = tempfile.gettempdir()
  346. if tmp:
  347. tmpdir = os.path.join(
  348. tmp, "grass7-%(user)s-%(lock)s" % {'user': user,
  349. 'lock': gis_lock})
  350. try:
  351. os.mkdir(tmpdir, 0o700)
  352. except:
  353. tmp = None
  354. if not tmp:
  355. for ttmp in ("/tmp", "/var/tmp", "/usr/tmp"):
  356. tmp = ttmp
  357. tmpdir = os.path.join(
  358. tmp, "grass7-%(user)s-%(lock)s" % {'user': user,
  359. 'lock': gis_lock})
  360. try:
  361. os.mkdir(tmpdir, 0o700)
  362. except:
  363. tmp = None
  364. if tmp:
  365. break
  366. if not tmp:
  367. fatal(_("Unable to create temporary directory <grass7-%(user)s-"
  368. "%(lock)s>! Exiting.") % {'user': user, 'lock': gis_lock})
  369. # promoting the variable even if it was not defined before
  370. os.environ['TMPDIR'] = tmpdir
  371. debug("Tmp directory '{tmpdir}' created for user '{user}'".format(
  372. tmpdir=tmpdir, user=user))
  373. return tmpdir
  374. def get_gisrc_from_config_dir(grass_config_dir, batch_job):
  375. """Set the global grassrc file (aka grassrcrc)"""
  376. if batch_job:
  377. # use individual GISRCRC files when in batch mode (r33174)
  378. filename = os.path.join(grass_config_dir, "rc.%s" % platform.node())
  379. if os.access(filename, os.R_OK):
  380. return filename
  381. # use standard file if in normal mode or the special file is not available
  382. return os.path.join(grass_config_dir, "rc")
  383. def create_gisrc(tmpdir, gisrcrc):
  384. # Set the session grassrc file
  385. gisrc = os.path.join(tmpdir, "gisrc")
  386. os.environ['GISRC'] = gisrc
  387. # remove invalid GISRC file to avoid disturbing error messages:
  388. try:
  389. s = readfile(gisrcrc)
  390. if "UNKNOWN" in s:
  391. try_remove(gisrcrc)
  392. s = None
  393. except:
  394. s = None
  395. # Copy the global grassrc file to the session grassrc file
  396. if s:
  397. writefile(gisrc, s)
  398. return gisrc
  399. def read_gisrc(filename):
  400. kv = {}
  401. try:
  402. f = open(filename, 'r')
  403. except IOError:
  404. return kv
  405. for line in f:
  406. try:
  407. k, v = line.split(':', 1)
  408. except ValueError as e:
  409. warning(_("Invalid line in RC file ({file}):"
  410. " '{line}' ({error})\n").format(
  411. line=line, error=e, file=filename))
  412. continue
  413. kv[k.strip()] = v.strip()
  414. if not kv:
  415. warning(_("Empty RC file ({file})").format(file=filename))
  416. f.close()
  417. return kv
  418. def read_env_file(path):
  419. kv = {}
  420. f = open(path, 'r')
  421. for line in f:
  422. k, v = line.split(':', 1)
  423. kv[k.strip()] = v.strip()
  424. f.close()
  425. return kv
  426. def write_gisrc(kv, filename):
  427. f = open(filename, 'w')
  428. for k, v in kv.items():
  429. f.write("%s: %s\n" % (k, v))
  430. f.close()
  431. def read_gui(gisrc, default_gui):
  432. grass_gui = None
  433. # At this point the GRASS user interface variable has been set from the
  434. # command line, been set from an external environment variable,
  435. # or is not set. So we check if it is not set
  436. # Check for a reference to the GRASS user interface in the grassrc file
  437. if os.access(gisrc, os.R_OK):
  438. kv = read_gisrc(gisrc)
  439. if 'GRASS_GUI' in os.environ:
  440. grass_gui = os.environ['GRASS_GUI']
  441. elif 'GUI' in kv:
  442. grass_gui = kv['GUI']
  443. elif 'GRASS_GUI' in kv:
  444. # For backward compatibility (GRASS_GUI renamed to GUI)
  445. grass_gui = kv['GRASS_GUI']
  446. else:
  447. # Set the GRASS user interface to the default if needed
  448. grass_gui = default_gui
  449. if not grass_gui:
  450. grass_gui = default_gui
  451. if grass_gui == 'gui':
  452. grass_gui = default_gui
  453. # FIXME oldtcltk, gis.m, d.m no longer exist (remove this around 7.2)
  454. if grass_gui in ['d.m', 'gis.m', 'oldtcltk', 'tcltk']:
  455. warning(_("GUI <%s> not supported in this version") % grass_gui)
  456. grass_gui = default_gui
  457. return grass_gui
  458. def path_prepend(directory, var):
  459. path = os.getenv(var)
  460. if path:
  461. path = directory + os.pathsep + path
  462. else:
  463. path = directory
  464. os.environ[var] = path
  465. def path_append(directory, var):
  466. path = os.getenv(var)
  467. if path:
  468. path = path + os.pathsep + directory
  469. else:
  470. path = directory
  471. os.environ[var] = path
  472. def set_paths(grass_config_dir):
  473. # addons (path)
  474. addon_path = os.getenv('GRASS_ADDON_PATH')
  475. if addon_path:
  476. for path in addon_path.split(os.pathsep):
  477. path_prepend(addon_path, 'PATH')
  478. # addons (base)
  479. addon_base = os.getenv('GRASS_ADDON_BASE')
  480. if not addon_base:
  481. addon_base = os.path.join(grass_config_dir, 'addons')
  482. os.environ['GRASS_ADDON_BASE'] = addon_base
  483. if not WINDOWS:
  484. path_prepend(os.path.join(addon_base, 'scripts'), 'PATH')
  485. path_prepend(os.path.join(addon_base, 'bin'), 'PATH')
  486. # standard installation
  487. if not WINDOWS:
  488. path_prepend(gpath('scripts'), 'PATH')
  489. path_prepend(gpath('bin'), 'PATH')
  490. # Set PYTHONPATH to find GRASS Python modules
  491. if os.path.exists(gpath('etc', 'python')):
  492. pythonpath = gpath('etc', 'python')
  493. path_prepend(pythonpath, 'PYTHONPATH')
  494. # the env var PYTHONPATH is only evaluated when python is started,
  495. # thus:
  496. sys.path.append(pythonpath)
  497. # now we can import stuff from GRASS lib/python
  498. # set path for the GRASS man pages
  499. grass_man_path = gpath('docs', 'man')
  500. addons_man_path = os.path.join(addon_base, 'docs', 'man')
  501. man_path = os.getenv('MANPATH')
  502. sys_man_path = None
  503. if man_path:
  504. path_prepend(addons_man_path, 'MANPATH')
  505. path_prepend(grass_man_path, 'MANPATH')
  506. else:
  507. try:
  508. nul = open(os.devnull, 'w')
  509. p = Popen(['manpath'], stdout=subprocess.PIPE, stderr=nul)
  510. nul.close()
  511. s = p.stdout.read()
  512. p.wait()
  513. sys_man_path = s.strip()
  514. except:
  515. pass
  516. if sys_man_path:
  517. os.environ['MANPATH'] = to_text_string(sys_man_path)
  518. path_prepend(addons_man_path, 'MANPATH')
  519. path_prepend(grass_man_path, 'MANPATH')
  520. else:
  521. os.environ['MANPATH'] = to_text_string(addons_man_path)
  522. path_prepend(grass_man_path, 'MANPATH')
  523. # Set LD_LIBRARY_PATH (etc) to find GRASS shared libraries
  524. # this works for subprocesses but won't affect the current process
  525. path_prepend(gpath("lib"), LD_LIBRARY_PATH_VAR)
  526. def find_exe(pgm):
  527. for directory in os.getenv('PATH').split(os.pathsep):
  528. path = os.path.join(directory, pgm)
  529. if os.access(path, os.X_OK):
  530. return path
  531. return None
  532. def set_defaults():
  533. # GRASS_PAGER
  534. if not os.getenv('GRASS_PAGER'):
  535. if find_exe("more"):
  536. pager = "more"
  537. elif find_exe("less"):
  538. pager = "less"
  539. elif WINDOWS:
  540. pager = "more"
  541. else:
  542. pager = "cat"
  543. os.environ['GRASS_PAGER'] = pager
  544. # GRASS_PYTHON
  545. if not os.getenv('GRASS_PYTHON'):
  546. if WINDOWS:
  547. os.environ['GRASS_PYTHON'] = "python.exe"
  548. else:
  549. os.environ['GRASS_PYTHON'] = "python"
  550. # GRASS_GNUPLOT
  551. if not os.getenv('GRASS_GNUPLOT'):
  552. os.environ['GRASS_GNUPLOT'] = "gnuplot -persist"
  553. # GRASS_PROJSHARE
  554. if not os.getenv('GRASS_PROJSHARE'):
  555. os.environ['GRASS_PROJSHARE'] = CONFIG_PROJSHARE
  556. def set_display_defaults():
  557. """ Predefine monitor size for certain architectures"""
  558. if os.getenv('HOSTTYPE') == 'arm':
  559. # small monitor on ARM (iPAQ, zaurus... etc)
  560. os.environ['GRASS_RENDER_HEIGHT'] = "320"
  561. os.environ['GRASS_RENDER_WIDTH'] = "240"
  562. def set_browser():
  563. # GRASS_HTML_BROWSER
  564. browser = os.getenv('GRASS_HTML_BROWSER')
  565. if not browser:
  566. if MACOSX:
  567. # OSX doesn't execute browsers from the shell PATH - route through a
  568. # script
  569. browser = gpath('etc', "html_browser_mac.sh")
  570. os.environ['GRASS_HTML_BROWSER_MACOSX'] = "-b com.apple.helpviewer"
  571. if WINDOWS:
  572. browser = "start"
  573. elif CYGWIN:
  574. browser = "explorer"
  575. else:
  576. # the usual suspects
  577. browsers = ["xdg-open", "x-www-browser", "htmlview", "konqueror", "mozilla",
  578. "mozilla-firefox", "firefox", "iceweasel", "opera",
  579. "netscape", "dillo", "lynx", "links", "w3c"]
  580. for b in browsers:
  581. if find_exe(b):
  582. browser = b
  583. break
  584. elif MACOSX:
  585. # OSX doesn't execute browsers from the shell PATH - route through a
  586. # script
  587. os.environ['GRASS_HTML_BROWSER_MACOSX'] = "-b %s" % browser
  588. browser = gpath('etc', "html_browser_mac.sh")
  589. if not browser:
  590. # even so we set to 'xdg-open' as a generic fallback
  591. browser = "xdg-open"
  592. os.environ['GRASS_HTML_BROWSER'] = browser
  593. def ensure_home():
  594. """Set HOME if not set on MS Windows"""
  595. if WINDOWS and not os.getenv('HOME'):
  596. os.environ['HOME'] = os.path.join(os.getenv('HOMEDRIVE'),
  597. os.getenv('HOMEPATH'))
  598. def create_initial_gisrc(filename):
  599. # for convenience, define GISDBASE as pwd:
  600. s = r"""GISDBASE: %s
  601. LOCATION_NAME: <UNKNOWN>
  602. MAPSET: <UNKNOWN>
  603. """ % os.getcwd()
  604. writefile(filename, s)
  605. def check_gui(expected_gui):
  606. grass_gui = expected_gui
  607. # Check if we are running X windows by checking the DISPLAY variable
  608. if os.getenv('DISPLAY') or WINDOWS or MACOSX:
  609. # Check if python is working properly
  610. if expected_gui in ('wxpython', 'gtext'):
  611. nul = open(os.devnull, 'w')
  612. p = Popen([os.environ['GRASS_PYTHON']], stdin=subprocess.PIPE,
  613. stdout=nul, stderr=nul)
  614. nul.close()
  615. p.stdin.write("variable=True".encode(ENCODING))
  616. p.stdin.close()
  617. p.wait()
  618. msg = None
  619. if p.returncode != 0:
  620. # Python was not found - switch to text interface mode
  621. msg = _("The python command does not work as expected!\n"
  622. "Please check your GRASS_PYTHON environment variable.\n"
  623. "Use the -help option for details.\n")
  624. if not os.path.exists(wxpath("wxgui.py")):
  625. msg = _("GRASS GUI not found. Please check your installation.")
  626. if msg:
  627. warning(_("{}\nSwitching to text based interface mode.\n\n"
  628. "Hit RETURN to continue.\n").format(msg))
  629. sys.stdin.readline()
  630. grass_gui = 'text'
  631. else:
  632. # Display a message if a graphical interface was expected
  633. if expected_gui != 'text':
  634. # Set the interface mode to text
  635. warning(_("It appears that the X Windows system is not active.\n"
  636. "A graphical based user interface is not supported.\n"
  637. "(DISPLAY variable is not set.)\n"
  638. "Switching to text based interface mode.\n\n"
  639. "Hit RETURN to continue.\n"))
  640. sys.stdin.readline()
  641. grass_gui = 'text'
  642. return grass_gui
  643. def save_gui(gisrc, grass_gui):
  644. """Save the user interface variable in the grassrc file"""
  645. if os.access(gisrc, os.F_OK):
  646. kv = read_gisrc(gisrc)
  647. kv['GUI'] = grass_gui
  648. write_gisrc(kv, gisrc)
  649. def create_location(gisdbase, location, geostring):
  650. """Create GRASS Location using georeferenced file or EPSG
  651. EPSG code format is ``EPSG:code`` or ``EPSG:code:datum_trans``.
  652. :param gisdbase: Path to GRASS GIS database directory
  653. :param location: name of new Location
  654. :param geostring: path to a georeferenced file or EPSG code
  655. """
  656. if gpath('etc', 'python') not in sys.path:
  657. sys.path.append(gpath('etc', 'python'))
  658. from grass.script import core as gcore # pylint: disable=E0611
  659. try:
  660. if geostring and geostring.upper().find('EPSG:') > -1:
  661. # create location using EPSG code
  662. epsg = geostring.split(':', 1)[1]
  663. if ':' in epsg:
  664. epsg, datum_trans = epsg.split(':', 1)
  665. else:
  666. datum_trans = None
  667. gcore.create_location(gisdbase, location,
  668. epsg=epsg, datum_trans=datum_trans)
  669. elif geostring == 'XY':
  670. # create an XY location
  671. gcore.create_location(gisdbase, location)
  672. else:
  673. # create location using georeferenced file
  674. gcore.create_location(gisdbase, location,
  675. filename=geostring)
  676. except gcore.ScriptError as err:
  677. fatal(err.value.strip('"').strip("'").replace('\\n', os.linesep))
  678. # TODO: distinguish between valid for getting maps and usable as current
  679. # https://lists.osgeo.org/pipermail/grass-dev/2016-September/082317.html
  680. # interface created according to the current usage
  681. def is_mapset_valid(full_mapset):
  682. """Return True if GRASS Mapset is valid"""
  683. # WIND is created from DEFAULT_WIND by `g.region -d` and functions
  684. # or modules which create a new mapset. Most modules will fail if
  685. # WIND doesn't exist (assuming that neither GRASS_REGION nor
  686. # WIND_OVERRIDE environmental variables are set).
  687. return os.access(os.path.join(full_mapset, "WIND"), os.R_OK)
  688. def is_location_valid(gisdbase, location):
  689. """Return True if GRASS Location is valid
  690. :param gisdbase: Path to GRASS GIS database directory
  691. :param location: name of a Location
  692. """
  693. # DEFAULT_WIND file should not be required until you do something
  694. # that actually uses them. The check is just a heuristic; a directory
  695. # containing a PERMANENT/DEFAULT_WIND file is probably a GRASS
  696. # location, while a directory lacking it probably isn't.
  697. return os.access(os.path.join(gisdbase, location,
  698. "PERMANENT", "DEFAULT_WIND"), os.F_OK)
  699. # basically checking location, possibly split into two functions
  700. # (mapset one can call location one)
  701. def get_mapset_invalid_reason(gisdbase, location, mapset):
  702. """Returns a message describing what is wrong with the Mapset
  703. The goal is to provide the most suitable error message
  704. (rather than to do a quick check).
  705. :param gisdbase: Path to GRASS GIS database directory
  706. :param location: name of a Location
  707. :param mapset: name of a Mapset
  708. :returns: translated message
  709. """
  710. full_location = os.path.join(gisdbase, location)
  711. full_permanent = os.path.join(full_location, 'PERMANENT')
  712. full_mapset = os.path.join(full_location, mapset)
  713. # first checking the location validity
  714. if not os.path.exists(full_location):
  715. return _("Location <%s> doesn't exist") % full_location
  716. elif 'PERMANENT' not in os.listdir(full_location):
  717. return _("<%s> is not a valid GRASS Location"
  718. " because PERMANENT Mapset is missing") % full_location
  719. elif not os.path.isdir(full_permanent):
  720. return _("<%s> is not a valid GRASS Location"
  721. " because PERMANENT is not a directory") % full_location
  722. # partially based on the is_location_valid() function
  723. elif not os.path.isfile(os.path.join(full_permanent,
  724. 'DEFAULT_WIND')):
  725. return _("<%s> is not a valid GRASS Location"
  726. " because PERMANENT Mapset does not have a DEFAULT_WIND file"
  727. " (default computational region)") % full_location
  728. # if location is valid, check mapset
  729. elif mapset not in os.listdir(full_location):
  730. return _("Mapset <{mapset}> doesn't exist in GRASS Location <{loc}>. "
  731. "A new mapset can be created by '-c' switch.").format(
  732. mapset=mapset, loc=location)
  733. elif not os.path.isdir(full_mapset):
  734. return _("<%s> is not a GRASS Mapset"
  735. " because it is not a directory") % mapset
  736. elif not os.path.isfile(os.path.join(full_mapset, 'WIND')):
  737. return _("<%s> is not a valid GRASS Mapset"
  738. " because it does not have a WIND file") % mapset
  739. # based on the is_mapset_valid() function
  740. elif not os.access(os.path.join(full_mapset, "WIND"), os.R_OK):
  741. return _("<%s> is not a valid GRASS Mapset"
  742. " because its WIND file is not readable") % mapset
  743. else:
  744. return _("Mapset <{mapset}> or Location <{location}> is"
  745. " invalid for an unknown reason").format(
  746. mapset=mapset, loc=location)
  747. def can_create_location(gisdbase, location):
  748. """Checks if location can be created"""
  749. path = os.path.join(gisdbase, location)
  750. if os.path.exists(path):
  751. return False
  752. return True
  753. def cannot_create_location_reason(gisdbase, location):
  754. """Returns a message describing why location cannot be created
  755. The goal is to provide the most suitable error message
  756. (rather than to do a quick check).
  757. :param gisdbase: Path to GRASS GIS database directory
  758. :param location: name of a Location
  759. :returns: translated message
  760. """
  761. path = os.path.join(gisdbase, location)
  762. if is_location_valid(gisdbase, location):
  763. return _("Unable to create new location because"
  764. " the location <{location}>"
  765. " already exists.").format(**locals())
  766. elif os.path.isfile(path):
  767. return _("Unable to create new location <{location}> because"
  768. " <{path}> is a file.").format(**locals())
  769. elif os.path.isdir(path):
  770. return _("Unable to create new location <{location}> because"
  771. " the directory <{path}>"
  772. " already exists.").format(**locals())
  773. else:
  774. return _("Unable to create new location in"
  775. " the directory <{path}>"
  776. " for an unknown reason.").format(**locals())
  777. def set_mapset(gisrc, arg=None, geofile=None, create_new=False,
  778. tmp_location=False, tmpdir=None):
  779. """Selected Location and Mapset are checked and created if requested
  780. The gisrc (GRASS environment file) is written at the end
  781. (nothing is returned).
  782. tmp_location requires tmpdir (which is used as gisdbase)
  783. """
  784. # TODO: arg param seems to be always the mapset parameter (or a dash
  785. # in a distant past), refactor
  786. l = arg
  787. if l:
  788. if l == '.':
  789. l = os.getcwd()
  790. elif not os.path.isabs(l):
  791. l = os.path.abspath(l)
  792. l, mapset = os.path.split(l)
  793. if not mapset:
  794. l, mapset = os.path.split(l)
  795. l, location_name = os.path.split(l)
  796. gisdbase = l
  797. # all was None for tmp loc so that case goes here quickly
  798. # TODO: but the above code needs review anyway
  799. if tmp_location:
  800. # set gisdbase to temporary directory
  801. gisdbase = tmpdir
  802. # we are already in a unique directory, so we can use fixed name
  803. location_name = "tmploc"
  804. # we need only one mapset
  805. mapset = "PERMANENT"
  806. debug("Using temporary location <{gdb}{sep}{lc}>".format(
  807. gdb=gisdbase, lc=location_name, sep=os.path.sep))
  808. if gisdbase and location_name and mapset:
  809. path = os.path.join(gisdbase, location_name, mapset)
  810. # check if 'path' is a valid GRASS location/mapset
  811. path_is_valid_mapset = is_mapset_valid(path)
  812. if path_is_valid_mapset and create_new:
  813. warning(_("Mapset <{}> already exists. Ignoring the"
  814. " request to create it. Note that this warning"
  815. " may become an error in future versions.")
  816. .format(path))
  817. if not path_is_valid_mapset:
  818. if not create_new:
  819. # 'path' is not a valid mapset and user does not
  820. # want to create anything new
  821. fatal(get_mapset_invalid_reason(gisdbase, location_name, mapset))
  822. else:
  823. # 'path' is not valid and the user wants to create
  824. # mapset on the fly
  825. # check if 'location_name' is a valid GRASS location
  826. if not is_location_valid(gisdbase, location_name):
  827. if not tmp_location:
  828. # 'location_name' is not a valid GRASS location
  829. # and user requested its creation, so we parsed
  830. # the path wrong and need to move one level
  831. # and use 'PERMANENT' mapset
  832. # (we already got that right in case of tmploc)
  833. gisdbase = os.path.join(gisdbase, location_name)
  834. location_name = mapset
  835. mapset = "PERMANENT"
  836. if not can_create_location(gisdbase, location_name):
  837. fatal(cannot_create_location_reason(
  838. gisdbase, location_name))
  839. # create new location based on the provided EPSG/...
  840. message(_("Creating new GRASS GIS location <{}>...")
  841. .format(location_name))
  842. create_location(gisdbase, location_name, geofile)
  843. else:
  844. # 'location_name' is a valid GRASS location,
  845. # create new mapset
  846. message(_("Creating new GRASS GIS mapset <{}>...")
  847. .format(mapset))
  848. if os.path.isfile(path):
  849. # not a valid mapset, but dir exists, assuming
  850. # broken/incomplete mapset
  851. fatal(_("Unable to create new mapset <{mapset}>"
  852. " because <{path}> is a file.")
  853. .format(mapset=mapset, path=path))
  854. elif os.path.isdir(path):
  855. # not a valid mapset, but dir exists, assuming
  856. # broken/incomplete mapset
  857. warning(_("The mapset <{}> is missing the WIND file"
  858. " (computational region). It will be"
  859. " fixed now. Note that this warning"
  860. " may become an error in future versions.")
  861. .format(mapset))
  862. else:
  863. # create mapset directory
  864. os.mkdir(path)
  865. # make directory a mapset, add the region
  866. # copy PERMANENT/DEFAULT_WIND to <mapset>/WIND
  867. s = readfile(os.path.join(gisdbase, location_name,
  868. "PERMANENT", "DEFAULT_WIND"))
  869. writefile(os.path.join(path, "WIND"), s)
  870. if os.access(gisrc, os.R_OK):
  871. kv = read_gisrc(gisrc)
  872. else:
  873. kv = {}
  874. kv['GISDBASE'] = gisdbase
  875. kv['LOCATION_NAME'] = location_name
  876. kv['MAPSET'] = mapset
  877. write_gisrc(kv, gisrc)
  878. else:
  879. fatal(_("GRASS GIS database directory, location and mapset"
  880. " not set properly."
  881. " Use GUI or command line to set them."))
  882. def set_mapset_interactive(grass_gui):
  883. """User selects Location and Mapset in an interative way
  884. The gisrc (GRASS environment file) is written at the end.
  885. """
  886. if not os.path.exists(wxpath("gis_set.py")) and grass_gui != 'text':
  887. debug("No GUI available, switching to text mode")
  888. return False
  889. # Check for text interface
  890. if grass_gui == 'text':
  891. # TODO: maybe this should be removed and solved from outside
  892. # this depends on what we expect from this function
  893. # should gisrc be ok after running or is it allowed to be still not set
  894. pass
  895. # Check for GUI
  896. elif grass_gui in ('gtext', 'wxpython'):
  897. gui_startup(grass_gui)
  898. else:
  899. # Shouldn't need this but you never know
  900. fatal(_("Invalid user interface specified - <%s>. "
  901. "Use the --help option to see valid interface names.") % grass_gui)
  902. return True
  903. def gui_startup(grass_gui):
  904. """Start GUI for startup (setting gisrc file)"""
  905. if grass_gui in ('wxpython', 'gtext'):
  906. ret = call([os.getenv('GRASS_PYTHON'), wxpath("gis_set.py")])
  907. # this if could be simplified to three branches (0, 5, rest)
  908. # if there is no need to handle unknown code separately
  909. if ret == 0:
  910. pass
  911. elif ret in [1, 2]:
  912. # 1 probably error coming from gis_set.py
  913. # 2 probably file not found from python interpreter
  914. # formerly we were starting in text mode instead, now we just fail
  915. # which is more straightforward for everybody
  916. fatal(_("Error in GUI startup. See messages above (if any)"
  917. " and if necessary, please"
  918. " report this error to the GRASS developers.\n"
  919. "On systems with package manager, make sure you have the right"
  920. " GUI package, probably named grass-gui, installed.\n"
  921. "To run GRASS GIS in text mode use the --text flag.\n"
  922. "Use '--help' for further options\n"
  923. " {cmd_name} --help\n"
  924. "See also: https://grass.osgeo.org/{cmd_name}/manuals/helptext.html").format(
  925. cmd_name=CMD_NAME))
  926. elif ret == 5: # defined in gui/wxpython/gis_set.py
  927. # User wants to exit from GRASS
  928. message(_("Exit was requested in GUI.\nGRASS GIS will not start. Bye."))
  929. sys.exit(0)
  930. else:
  931. fatal(_("Invalid return code from GUI startup script.\n"
  932. "Please advise GRASS developers of this error."))
  933. # we don't follow the LOCATION_NAME legacy naming here but we have to still
  934. # translate to it, so always double check
  935. class MapsetSettings(object):
  936. """Holds GRASS GIS database directory, Location and Mapset
  937. Provides few convenient functions.
  938. """
  939. def __init__(self):
  940. self.gisdbase = None
  941. self.location = None
  942. self.mapset = None
  943. self._full_mapset = None
  944. # TODO: perhaps full_mapset would be better as mapset_path
  945. # TODO: works only when set for the first time
  946. # this follows the current usage but we must invalidate when
  947. # the others are changed (use properties for that)
  948. @property
  949. def full_mapset(self):
  950. if self._full_mapset is None:
  951. self._full_mapset = os.path.join(self.gisdbase, self.location,
  952. self.mapset)
  953. return self._full_mapset
  954. # TODO: perhaps conversion to bool would be nicer
  955. def is_valid(self):
  956. return self.gisdbase and self.location and self.mapset
  957. # TODO: does it really makes sense to tell user about gisrcrc?
  958. # anything could have happened in between loading from gisrcrc and now
  959. # (we do e.g. GUI or creating loctation)
  960. def load_gisrc(gisrc, gisrcrc):
  961. """Get the settings of Location and Mapset from the gisrc file
  962. :returns: MapsetSettings object
  963. """
  964. mapset_settings = MapsetSettings()
  965. kv = read_gisrc(gisrc)
  966. mapset_settings.gisdbase = kv.get('GISDBASE')
  967. mapset_settings.location = kv.get('LOCATION_NAME')
  968. mapset_settings.mapset = kv.get('MAPSET')
  969. if not mapset_settings.is_valid():
  970. fatal(_("Error reading data path information from g.gisenv.\n"
  971. "GISDBASE={gisdbase}\n"
  972. "LOCATION_NAME={location}\n"
  973. "MAPSET={mapset}\n\n"
  974. "Check the <{file}> file.").format(
  975. gisdbase=mapset_settings.gisdbase,
  976. location=mapset_settings.location,
  977. mapset=mapset_settings.mapset,
  978. file=gisrcrc))
  979. return mapset_settings
  980. # load environmental variables from grass_env_file
  981. def load_env(grass_env_file):
  982. if not os.access(grass_env_file, os.R_OK):
  983. return
  984. for line in readfile(grass_env_file).split(os.linesep):
  985. try:
  986. k, v = map(lambda x: x.strip(), line.strip().split(' ', 1)[1].split('=', 1))
  987. except:
  988. continue
  989. debug("Environmental variable set {0}={1}".format(k, v))
  990. os.environ[k] = v
  991. # Allow for mixed ISIS-GRASS Environment
  992. if os.getenv('ISISROOT'):
  993. isis = os.getenv('ISISROOT')
  994. os.environ['ISIS_LIB'] = isis + os.sep + "lib"
  995. os.environ['ISIS_3RDPARTY'] = isis + os.sep + "3rdParty" + os.sep + "lib"
  996. os.environ['QT_PLUGIN_PATH'] = isis + os.sep + "3rdParty" + os.sep + "plugins"
  997. # os.environ['ISIS3DATA'] = isis + "$ISIS3DATA"
  998. libpath = os.getenv('LD_LIBRARY_PATH', '')
  999. isislibpath = os.getenv('ISIS_LIB')
  1000. isis3rdparty = os.getenv('ISIS_3RDPARTY')
  1001. os.environ['LD_LIBRARY_PATH'] = libpath + os.pathsep + isislibpath + os.pathsep + isis3rdparty
  1002. def set_language(grass_config_dir):
  1003. # This function is used to override system default language and locale
  1004. # Such override can be requested only from wxGUI
  1005. # An override if user has provided correct environmental variables as
  1006. # LC_MESSAGES or LANG is not necessary.
  1007. # Unfortunately currently a working solution for Windows is lacking
  1008. # thus it always on Vista and XP will print an error.
  1009. # See discussion for Windows not following its own documentation and
  1010. # not accepting ISO codes as valid locale identifiers http://bugs.python.org/issue10466
  1011. language = 'None' # Such string sometimes is present in wx file
  1012. encoding = None
  1013. # Override value is stored in wxGUI preferences file.
  1014. # As it's the only thing required, we'll just grep it out.
  1015. try:
  1016. fd = open(os.path.join(grass_config_dir, 'wx'), 'r')
  1017. except:
  1018. # Even if there is no override, we still need to set locale.
  1019. pass
  1020. else:
  1021. for line in fd:
  1022. if re.search('^language', line):
  1023. line = line.rstrip(' %s' % os.linesep)
  1024. language = ''.join(line.split(';')[-1:])
  1025. break
  1026. fd.close()
  1027. # Backwards compatibility with old wx preferences files
  1028. if language == 'C':
  1029. language = 'en'
  1030. if language == 'None' or language == '' or not language:
  1031. # Language override is disabled (system language specified)
  1032. # As by default program runs with C locale, but users expect to
  1033. # have their default locale, we'll just set default locale
  1034. try:
  1035. locale.setlocale(locale.LC_ALL, '')
  1036. except locale.Error as e:
  1037. # If we get here, system locale settings are terribly wrong
  1038. # There is no point to continue as GRASS/Python will fail
  1039. # in some other unpredictable way.
  1040. sys.stderr.write(
  1041. "System locale is not usable (LC_ALL variable not defined)."
  1042. " Most likely it indicates misconfigured environment.\n")
  1043. sys.stderr.write("Reported error message: %s\n" % e)
  1044. # it would be too drastic to exit
  1045. # sys.exit("Fix system locale settings and then try again.")
  1046. locale.setlocale(locale.LC_ALL, 'C')
  1047. sys.stderr.write("Default locale settings are missing. GRASS running with C locale.")
  1048. language, encoding = locale.getdefaultlocale()
  1049. if not language:
  1050. sys.stderr.write("Default locale settings are missing. GRASS running with C locale.")
  1051. return
  1052. else:
  1053. debug("A language override has been requested."
  1054. " Trying to switch GRASS into '%s'..." % language)
  1055. try:
  1056. locale.setlocale(locale.LC_ALL, language)
  1057. except locale.Error as e:
  1058. try:
  1059. # Locale lang.encoding might be missing. Let's try
  1060. # UTF-8 encoding before giving up as on Linux systems
  1061. # lang.UTF-8 locales are more common than legacy
  1062. # ISO-8859 ones.
  1063. encoding = 'UTF-8'
  1064. normalized = locale.normalize('%s.%s' % (language, encoding))
  1065. locale.setlocale(locale.LC_ALL, normalized)
  1066. except locale.Error as e:
  1067. if language == 'en':
  1068. # A workaround for Python Issue30755
  1069. # https://bugs.python.org/issue30755
  1070. if locale.normalize('C.UTF-8') == 'en_US.UTF-8':
  1071. locale.setlocale(locale.LC_ALL, 'C')
  1072. os.environ['LANGUAGE'] = 'C'
  1073. os.environ['LANG'] = 'C'
  1074. os.environ['LC_MESSAGES'] = 'C'
  1075. os.environ['LC_NUMERIC'] = 'C'
  1076. os.environ['LC_TIME'] = 'C'
  1077. sys.stderr.write(
  1078. "To avoid Unicode errors in GUI, install"
  1079. " en_US.UTF-8 locale and restart GRASS.\n"
  1080. "Also consider upgrading your Python version"
  1081. " to one containing fix for Python Issue 30755.\n")
  1082. return
  1083. # en_US locale might be missing, still all messages in
  1084. # GRASS are already in en_US language.
  1085. # Using plain C as locale forces encodings to ascii
  1086. # thus lets try our luck with C.UTF-8 first.
  1087. # See bugs #3441 and #3423
  1088. try:
  1089. locale.setlocale(locale.LC_ALL, 'C.UTF-8')
  1090. except locale.Error as e:
  1091. # All lost. Setting to C as much as possible.
  1092. # We can not call locale.normalize on C as it
  1093. # will transform it to en_US and we already know
  1094. # it doesn't work.
  1095. locale.setlocale(locale.LC_ALL, 'C')
  1096. os.environ['LANGUAGE'] = 'C'
  1097. os.environ['LANG'] = 'C'
  1098. os.environ['LC_MESSAGES'] = 'C'
  1099. os.environ['LC_NUMERIC'] = 'C'
  1100. os.environ['LC_TIME'] = 'C'
  1101. gettext.install('grasslibs', gpath('locale'))
  1102. sys.stderr.write(
  1103. "All attempts to enable English language have"
  1104. " failed. GRASS running with C locale.\n"
  1105. "If you observe UnicodeError in Python,"
  1106. " install en_US.UTF-8"
  1107. " locale and restart GRASS.\n")
  1108. return
  1109. else:
  1110. # The last attempt...
  1111. try:
  1112. encoding = locale.getpreferredencoding()
  1113. normalized = locale.normalize('%s.%s' % (language, encoding))
  1114. locale.setlocale(locale.LC_ALL, normalized)
  1115. except locale.Error as e:
  1116. # If we got so far, attempts to set up language and locale have failed
  1117. # on this system
  1118. sys.stderr.write("Failed to enforce user specified language '%s' with error: '%s'\n" % (language, e))
  1119. sys.stderr.write("A LANGUAGE environmental variable has been set.\nPart of messages will be displayed in the requested language.\n")
  1120. # Even if setting locale will fail, let's set LANG in a hope,
  1121. # that UI will use it GRASS texts will be in selected language,
  1122. # system messages (i.e. OK, Cancel etc.) - in system default
  1123. # language
  1124. os.environ['LANGUAGE'] = language
  1125. os.environ['LANG'] = language
  1126. return
  1127. # Set up environment for subprocesses
  1128. os.environ['LANGUAGE'] = language
  1129. os.environ['LANG'] = language
  1130. if language == 'ko_KR' and encoding == 'cp949':
  1131. # The default encoding for the Korean language in Windows is cp949,
  1132. # Microsoft's proprietary extension to euc-kr, but gettext prints no
  1133. # translated messages at all in the Command Prompt window if LC_CTYPE
  1134. # is set to ko_KR.cp949. Here, force LC_CTYPE to be euc-kr.
  1135. normalized = 'euc-kr'
  1136. encoding = None
  1137. elif encoding:
  1138. normalized = locale.normalize('%s.%s' % (language, encoding))
  1139. else:
  1140. normalized = language
  1141. for lc in ('LC_CTYPE', 'LC_MESSAGES', 'LC_TIME', 'LC_COLLATE',
  1142. 'LC_MONETARY', 'LC_PAPER', 'LC_NAME', 'LC_ADDRESS',
  1143. 'LC_TELEPHONE', 'LC_MEASUREMENT', 'LC_IDENTIFICATION'):
  1144. os.environ[lc] = normalized
  1145. # Some code in GRASS might not like other decimal separators than .
  1146. # Other potential sources for problems are: LC_TIME LC_CTYPE
  1147. locale.setlocale(locale.LC_NUMERIC, 'C')
  1148. os.environ['LC_NUMERIC'] = 'C'
  1149. if os.getenv('LC_ALL'):
  1150. del os.environ['LC_ALL'] # Remove LC_ALL to not override LC_NUMERIC
  1151. # From now on enforce the new language
  1152. if encoding:
  1153. gettext.install('grasslibs', gpath('locale'), codeset=encoding)
  1154. else:
  1155. gettext.install('grasslibs', gpath('locale'))
  1156. # TODO: grass_gui parameter is a hack and should be removed, see below
  1157. def lock_mapset(mapset_path, force_gislock_removal, user, grass_gui):
  1158. """Lock the mapset and return name of the lock file
  1159. Behavior on error must be changed somehow; now it fatals but GUI case is
  1160. unresolved.
  1161. """
  1162. if not os.path.exists(mapset_path):
  1163. fatal(_("Path '%s' doesn't exist") % mapset_path)
  1164. if not os.access(mapset_path, os.W_OK):
  1165. error = _("Path '%s' not accessible.") % mapset_path
  1166. stat_info = os.stat(mapset_path)
  1167. mapset_uid = stat_info.st_uid
  1168. if mapset_uid != os.getuid():
  1169. # GTC %s is mapset's folder path
  1170. error = "%s\n%s" % (error, _("You are not the owner of '%s'.") % mapset_path)
  1171. fatal(error)
  1172. # Check for concurrent use
  1173. lockfile = os.path.join(mapset_path, ".gislock")
  1174. ret = call([gpath("etc", "lock"), lockfile, "%d" % os.getpid()])
  1175. msg = None
  1176. if ret == 2:
  1177. if not force_gislock_removal:
  1178. msg = _("%(user)s is currently running GRASS in selected mapset"
  1179. " (file %(file)s found). Concurrent use not allowed.\n"
  1180. "You can force launching GRASS using -f flag"
  1181. " (note that you need permission for this operation)."
  1182. " Have another look in the processor "
  1183. "manager just to be sure..." % {
  1184. 'user': user, 'file': lockfile})
  1185. else:
  1186. try_remove(lockfile)
  1187. message(_("%(user)s is currently running GRASS in selected mapset"
  1188. " (file %(file)s found). Forcing to launch GRASS..." % {
  1189. 'user': user, 'file': lockfile}))
  1190. elif ret != 0:
  1191. msg = _("Unable to properly access '%s'.\n"
  1192. "Please notify system personnel.") % lockfile
  1193. # TODO: the gui decision should be done by the caller
  1194. # this needs some change to the function interface, return tuple or
  1195. # use exceptions (better option)
  1196. if msg:
  1197. if grass_gui == "wxpython":
  1198. call([os.getenv('GRASS_PYTHON'), wxpath("gis_set_error.py"), msg])
  1199. # TODO: here we probably miss fatal or exit, needs to be added
  1200. else:
  1201. fatal(msg)
  1202. debug("Mapset <{mapset}> locked using '{lockfile}'".format(
  1203. mapset=mapset_path, lockfile=lockfile))
  1204. return lockfile
  1205. # TODO: the gisrcrc here does not make sense, remove it from load_gisrc
  1206. def unlock_gisrc_mapset(gisrc, gisrcrc):
  1207. """Unlock mapset from the gisrc file"""
  1208. settings = load_gisrc(gisrc, gisrcrc)
  1209. lockfile = os.path.join(settings.full_mapset, ".gislock")
  1210. # this fails silently, perhaps a warning would be helpful to
  1211. # catch cases when removal was not possible due to e.g. another
  1212. # session force-removing the file (unlocking the mapset)
  1213. try_remove(lockfile)
  1214. def make_fontcap():
  1215. # TODO: is GRASS_FONT_CAP ever defined? It seems it must be defined in system
  1216. fc = os.getenv('GRASS_FONT_CAP')
  1217. if fc and not os.access(fc, os.R_OK):
  1218. message(_("Building user fontcap..."))
  1219. call(["g.mkfontcap"])
  1220. def ensure_db_connected(mapset):
  1221. """Predefine default driver if DB connection not defined
  1222. :param mapset: full path to the mapset
  1223. """
  1224. if not os.access(os.path.join(mapset, "VAR"), os.F_OK):
  1225. call(['db.connect', '-c', '--quiet'])
  1226. def get_shell():
  1227. # set SHELL on ms windowns
  1228. # this was at the very beginning of the script but it can be anywhere
  1229. if WINDOWS:
  1230. if os.getenv('GRASS_SH'):
  1231. os.environ['SHELL'] = os.getenv('GRASS_SH')
  1232. if not os.getenv('SHELL'):
  1233. os.environ['SHELL'] = os.getenv('COMSPEC', 'cmd.exe')
  1234. # cygwin has many problems with the shell setup
  1235. # below, so i hardcoded everything here.
  1236. if sys.platform == 'cygwin':
  1237. sh = "CYGWIN"
  1238. shellname = "GNU Bash (Cygwin)"
  1239. os.environ['SHELL'] = "/usr/bin/bash.exe"
  1240. os.environ['OSTYPE'] = "cygwin"
  1241. else:
  1242. # in docker the 'SHELL' variable may not be
  1243. # visible in a Python session unless 'ENV SHELL /bin/bash' is set in Dockerfile
  1244. try:
  1245. sh = os.path.basename(os.getenv('SHELL'))
  1246. except:
  1247. sh = 'sh'
  1248. os.environ['SHELL'] = sh
  1249. if WINDOWS and sh:
  1250. sh = os.path.splitext(sh)[0]
  1251. if sh == "ksh":
  1252. shellname = "Korn Shell"
  1253. elif sh == "csh":
  1254. shellname = "C Shell"
  1255. elif sh == "tcsh":
  1256. shellname = "TC Shell"
  1257. elif sh == "bash":
  1258. shellname = "Bash Shell"
  1259. elif sh == "sh":
  1260. shellname = "Bourne Shell"
  1261. elif sh == "zsh":
  1262. shellname = "Z Shell"
  1263. elif sh == "cmd":
  1264. shellname = "Command Prompt"
  1265. elif sh == "powershell":
  1266. shellname = "Windows PowerShell"
  1267. else:
  1268. shellname = "shell"
  1269. # check for SHELL
  1270. if not os.getenv('SHELL'):
  1271. fatal(_("The SHELL variable is not set"))
  1272. return sh, shellname
  1273. def get_grass_env_file(sh, grass_config_dir):
  1274. """Get name of the shell-specific GRASS environment (rc) file"""
  1275. if sh in ['csh', 'tcsh']:
  1276. grass_env_file = os.path.join(grass_config_dir, 'cshrc')
  1277. elif sh in ['bash', 'msh', 'cygwin', 'sh']:
  1278. grass_env_file = os.path.join(grass_config_dir, 'bashrc')
  1279. elif sh == 'zsh':
  1280. grass_env_file = os.path.join(grass_config_dir, 'zshrc')
  1281. elif sh in ['cmd', 'powershell']:
  1282. grass_env_file = os.path.join(grass_config_dir, 'env.bat')
  1283. else:
  1284. grass_env_file = os.path.join(grass_config_dir, 'bashrc')
  1285. warning(_("Unsupported shell <{sh}>: {env_file}").format(
  1286. sh=sh, env_file=grass_env_file))
  1287. return grass_env_file
  1288. def get_batch_job_from_env_variable():
  1289. """Get script to execute from batch job variable if available
  1290. Fails with fatal if variable is set but content unusable.
  1291. """
  1292. # hack to process batch jobs:
  1293. batch_job = os.getenv('GRASS_BATCH_JOB')
  1294. # variable defined, but user might not have been careful enough
  1295. if batch_job:
  1296. if not os.access(batch_job, os.F_OK):
  1297. # wrong file
  1298. fatal(_("Job file <%s> has been defined in "
  1299. "the 'GRASS_BATCH_JOB' variable but not found. Exiting."
  1300. "\n\n"
  1301. "Use 'unset GRASS_BATCH_JOB' to disable "
  1302. "batch job processing.") % batch_job)
  1303. elif not os.access(batch_job, os.X_OK):
  1304. # right file, but ...
  1305. fatal(_("Change file permission to 'executable' for <%s>")
  1306. % batch_job)
  1307. return batch_job
  1308. def run_batch_job(batch_job):
  1309. """Runs script, module or any command
  1310. If *batch_job* is a string (insecure) shell=True is used for execution.
  1311. :param batch_job: executable and parameters in a list or a string
  1312. """
  1313. batch_job_string = batch_job
  1314. if not isinstance(batch_job, six.string_types):
  1315. # for messages only
  1316. batch_job_string = ' '.join(batch_job)
  1317. message(_("Executing <%s> ...") % batch_job_string)
  1318. if isinstance(batch_job, six.string_types):
  1319. # shell=True is keeping the original GRASS_BATCH_JOB behavior
  1320. def quote(string):
  1321. if '"' in string:
  1322. return "'%s'" % batch_job
  1323. else:
  1324. return '"%s"' % batch_job
  1325. batch_job = quote(batch_job)
  1326. proc = Popen(batch_job, shell=True)
  1327. else:
  1328. try:
  1329. proc = Popen(batch_job, shell=False)
  1330. except OSError as error:
  1331. fatal(_("Execution of <{cmd}> failed:\n"
  1332. "{error}").format(cmd=batch_job_string, error=error))
  1333. returncode = proc.wait()
  1334. message(_("Execution of <%s> finished.") % batch_job_string)
  1335. return returncode
  1336. def start_gui(grass_gui):
  1337. """Start specified GUI
  1338. :param grass_gui: GUI name (allowed values: 'wxpython')
  1339. """
  1340. # Start the chosen GUI but ignore text
  1341. debug("GRASS GUI should be <%s>" % grass_gui)
  1342. # Check for gui interface
  1343. if grass_gui == "wxpython":
  1344. Popen([os.getenv('GRASS_PYTHON'), wxpath("wxgui.py")])
  1345. def close_gui():
  1346. """Close GUI if running"""
  1347. if gpath('etc', 'python') not in sys.path:
  1348. sys.path.append(gpath('etc', 'python'))
  1349. from grass.script import core as gcore # pylint: disable=E0611
  1350. env = gcore.gisenv()
  1351. if 'GUI_PID' not in env:
  1352. return
  1353. for pid in env['GUI_PID'].split(','):
  1354. debug("Exiting GUI with pid={0}".format(pid))
  1355. try:
  1356. os.kill(int(pid), signal.SIGTERM)
  1357. except OSError as e:
  1358. message(_("Unable to close GUI. {0}").format(e))
  1359. def show_banner():
  1360. """Write GRASS GIS ASCII name to stderr"""
  1361. sys.stderr.write(r"""
  1362. __________ ___ __________ _______________
  1363. / ____/ __ \/ | / ___/ ___/ / ____/ _/ ___/
  1364. / / __/ /_/ / /| | \__ \\_ \ / / __ / / \__ \
  1365. / /_/ / _, _/ ___ |___/ /__/ / / /_/ // / ___/ /
  1366. \____/_/ |_/_/ |_/____/____/ \____/___//____/
  1367. """)
  1368. def say_hello():
  1369. """Write welcome to stderr including Subversion revision if in svn copy"""
  1370. sys.stderr.write(_("Welcome to GRASS GIS %s") % GRASS_VERSION)
  1371. if GRASS_VERSION.endswith('svn'):
  1372. try:
  1373. filerev = open(gpath('etc', 'VERSIONNUMBER'))
  1374. linerev = filerev.readline().rstrip('\n')
  1375. filerev.close()
  1376. revision = linerev.split(' ')[1]
  1377. sys.stderr.write(' (' + revision + ')')
  1378. except:
  1379. pass
  1380. INFO_TEXT = r"""\
  1381. %-41shttps://grass.osgeo.org
  1382. %-41s%s (%s)
  1383. %-41sg.manual -i
  1384. %-41sg.version -c
  1385. %-41sg.version -x
  1386. """
  1387. def show_info(shellname, grass_gui, default_gui):
  1388. """Write basic info about GRASS GIS and GRASS session to stderr"""
  1389. sys.stderr.write(INFO_TEXT % (
  1390. _("GRASS GIS homepage:"),
  1391. # GTC Running through: SHELL NAME
  1392. _("This version running through:"),
  1393. shellname, os.getenv('SHELL'),
  1394. _("Help is available with the command:"),
  1395. _("See the licence terms with:"),
  1396. _("See citation options with:")))
  1397. if grass_gui == 'wxpython':
  1398. message("%-41sg.gui wxpython" % _("If required, restart the GUI with:"))
  1399. else:
  1400. message("%-41sg.gui %s" % (_("Start the GUI with:"), default_gui))
  1401. message("%-41sexit" % _("When ready to quit enter:"))
  1402. message("")
  1403. def csh_startup(location, location_name, mapset, grass_env_file):
  1404. userhome = os.getenv('HOME') # save original home
  1405. home = location
  1406. os.environ['HOME'] = home
  1407. cshrc = os.path.join(home, ".cshrc")
  1408. tcshrc = os.path.join(home, ".tcshrc")
  1409. try_remove(cshrc)
  1410. try_remove(tcshrc)
  1411. f = open(cshrc, 'w')
  1412. f.write("set home = %s\n" % userhome)
  1413. f.write("set history = 3000 savehist = 3000 noclobber ignoreeof\n")
  1414. f.write("set histfile = %s\n" % os.path.join(os.getenv('HOME'),
  1415. ".history"))
  1416. f.write("set prompt = '\\\n")
  1417. f.write("Mapset <%s> in Location <%s> \\\n" % (mapset, location_name))
  1418. f.write("GRASS GIS %s > '\n" % GRASS_VERSION)
  1419. f.write("set BOGUS=``;unset BOGUS\n")
  1420. # csh shell rc file left for backward compatibility
  1421. path = os.path.join(userhome, ".grass.cshrc")
  1422. if os.access(path, os.R_OK):
  1423. f.write(readfile(path) + '\n')
  1424. if os.access(grass_env_file, os.R_OK):
  1425. f.write(readfile(grass_env_file) + '\n')
  1426. mail_re = re.compile(r"^ *set *mail *= *")
  1427. for filename in [".cshrc", ".tcshrc", ".login"]:
  1428. path = os.path.join(userhome, filename)
  1429. if os.access(path, os.R_OK):
  1430. s = readfile(path)
  1431. lines = s.splitlines()
  1432. for l in lines:
  1433. if mail_re.match(l):
  1434. f.write(l)
  1435. path = os.getenv('PATH').split(':')
  1436. f.write("set path = ( %s ) \n" % ' '.join(path))
  1437. f.close()
  1438. writefile(tcshrc, readfile(cshrc))
  1439. process = Popen([gpath("etc", "run"), os.getenv('SHELL')])
  1440. os.environ['HOME'] = userhome
  1441. return process
  1442. def bash_startup(location, location_name, grass_env_file):
  1443. # save command history in mapset dir and remember more
  1444. os.environ['HISTFILE'] = os.path.join(location, ".bash_history")
  1445. if not os.getenv('HISTSIZE') and not os.getenv('HISTFILESIZE'):
  1446. os.environ['HISTSIZE'] = "3000"
  1447. # instead of changing $HOME, start bash with:
  1448. # --rcfile "$LOCATION/.bashrc" ?
  1449. # if so, must care be taken to explicitly call .grass.bashrc et al
  1450. # for non-interactive bash batch jobs?
  1451. userhome = os.getenv('HOME') # save original home
  1452. home = location # save .bashrc in $LOCATION
  1453. os.environ['HOME'] = home
  1454. bashrc = os.path.join(home, ".bashrc")
  1455. try_remove(bashrc)
  1456. f = open(bashrc, 'w')
  1457. f.write("test -r ~/.alias && . ~/.alias\n")
  1458. if os.getenv('ISISROOT'):
  1459. # GRASS GIS and ISIS blend
  1460. grass_name = "ISIS-GRASS"
  1461. else:
  1462. grass_name = "GRASS"
  1463. f.write("PS1='{name} {version} ({location}):\\w > '\n".format(
  1464. name=grass_name, version=GRASS_VERSION, location=location_name))
  1465. # TODO: have a function and/or module to test this
  1466. mask2d_test = 'test -f "$MAPSET_PATH/cell/MASK"'
  1467. mask3d_test = 'test -d "$MAPSET_PATH/grid3/RASTER3D_MASK"'
  1468. # double curly brackets means single one for format function
  1469. # setting LOCATION for backwards compatibility
  1470. f.write(
  1471. """grass_prompt() {{
  1472. MAPSET_PATH="`g.gisenv get=GISDBASE,LOCATION_NAME,MAPSET separator='/'`"
  1473. LOCATION="$MAPSET_PATH"
  1474. if {mask2d_test} && {mask3d_test} ; then
  1475. echo [{both_masks}]
  1476. elif {mask2d_test} ; then
  1477. echo [{mask2d}]
  1478. elif {mask3d_test} ; then
  1479. echo [{mask3d}]
  1480. fi
  1481. }}
  1482. PROMPT_COMMAND=grass_prompt\n""".format(
  1483. both_masks=_("2D and 3D raster MASKs present"),
  1484. mask2d=_("Raster MASK present"),
  1485. mask3d=_("3D raster MASK present"),
  1486. mask2d_test=mask2d_test, mask3d_test=mask3d_test
  1487. ))
  1488. # read other settings (aliases, ...) since environmental variables
  1489. # have been already set by load_env(), see #3462
  1490. for env_file in [os.path.join(userhome, ".grass.bashrc"),
  1491. grass_env_file]:
  1492. if not os.access(env_file, os.R_OK):
  1493. continue
  1494. for line in readfile(env_file).splitlines():
  1495. # Bug related to OS X "SIP", see
  1496. # https://trac.osgeo.org/grass/ticket/3462#comment:13
  1497. if MACOSX or not line.startswith('export'):
  1498. f.write(line + '\n')
  1499. f.write("export PATH=\"%s\"\n" % os.getenv('PATH'))
  1500. f.write("export HOME=\"%s\"\n" % userhome) # restore user home path
  1501. f.close()
  1502. process = Popen([gpath("etc", "run"), os.getenv('SHELL')])
  1503. os.environ['HOME'] = userhome
  1504. return process
  1505. def default_startup(location, location_name):
  1506. if WINDOWS:
  1507. os.environ['PS1'] = "GRASS %s> " % (GRASS_VERSION)
  1508. # "$ETC/run" doesn't work at all???
  1509. process = subprocess.Popen([os.getenv('SHELL')])
  1510. else:
  1511. os.environ['PS1'] = "GRASS %s (%s):\\w > " % (GRASS_VERSION, location_name)
  1512. process = Popen([gpath("etc", "run"), os.getenv('SHELL')])
  1513. return process
  1514. def done_message():
  1515. # here was something for batch job but it was never called
  1516. message(_("Done."))
  1517. message("")
  1518. message(_("Goodbye from GRASS GIS"))
  1519. message("")
  1520. def clean_temp():
  1521. message(_("Cleaning up temporary files..."))
  1522. nul = open(os.devnull, 'w')
  1523. call([gpath("etc", "clean_temp")], stdout=nul)
  1524. nul.close()
  1525. def clean_all():
  1526. from grass.script import setup as gsetup
  1527. # clean default sqlite db
  1528. gsetup.clean_default_db()
  1529. # remove leftover temp files
  1530. clean_temp()
  1531. # save 'last used' GISRC after removing variables which shouldn't
  1532. # be saved, e.g. d.mon related
  1533. clean_env()
  1534. def grep(pattern, lines):
  1535. """Search lines (list of strings) and return them when beginning matches.
  1536. >>> grep("a", ['abc', 'cab', 'sdr', 'aaa', 'sss'])
  1537. ['abc', 'aaa']
  1538. """
  1539. expr = re.compile(pattern)
  1540. return [elem for elem in lines if expr.match(elem)]
  1541. def print_params():
  1542. """Write compile flags and other configuration to stderr"""
  1543. plat = gpath('include', 'Make', 'Platform.make')
  1544. if not os.path.exists(plat):
  1545. fatal(_("Please install the GRASS GIS development package"))
  1546. fileplat = open(plat)
  1547. linesplat = fileplat.readlines()
  1548. fileplat.close()
  1549. params = sys.argv[2:]
  1550. if not params:
  1551. params = ['arch', 'build', 'compiler', 'path', 'revision', 'version']
  1552. for arg in params:
  1553. if arg == 'path':
  1554. sys.stdout.write("%s\n" % GISBASE)
  1555. elif arg == 'arch':
  1556. val = grep('ARCH', linesplat)
  1557. sys.stdout.write("%s\n" % val[0].split('=')[1].strip())
  1558. elif arg == 'build':
  1559. build = gpath('include', 'grass', 'confparms.h')
  1560. filebuild = open(build)
  1561. val = filebuild.readline()
  1562. filebuild.close()
  1563. sys.stdout.write("%s\n" % val.strip().strip('"').strip())
  1564. elif arg == 'compiler':
  1565. val = grep('CC', linesplat)
  1566. sys.stdout.write("%s\n" % val[0].split('=')[1].strip())
  1567. elif arg == 'revision':
  1568. rev = gpath('include', 'grass', 'gis.h')
  1569. filerev = open(rev)
  1570. linesrev = filerev.readlines()
  1571. val = grep('#define GIS_H_VERSION', linesrev)
  1572. filerev.close()
  1573. sys.stdout.write(
  1574. "%s\n" % val[0].split(':')[1].rstrip('$"\n').strip())
  1575. elif arg == 'svn_revision':
  1576. filerev = open(gpath('etc', 'VERSIONNUMBER'))
  1577. linerev = filerev.readline().rstrip('\n')
  1578. filerev.close()
  1579. try:
  1580. revision = linerev.split(' ')[1]
  1581. sys.stdout.write("%s\n" % revision[1:])
  1582. except:
  1583. sys.stdout.write("No SVN revision defined\n")
  1584. elif arg == 'version':
  1585. sys.stdout.write("%s\n" % GRASS_VERSION)
  1586. else:
  1587. message(_("Parameter <%s> not supported") % arg)
  1588. def get_username():
  1589. """Get name of the current user"""
  1590. if WINDOWS:
  1591. user = os.getenv('USERNAME')
  1592. if not user:
  1593. user = "user_name"
  1594. else:
  1595. user = os.getenv('USER')
  1596. if not user:
  1597. user = os.getenv('LOGNAME')
  1598. if not user:
  1599. try:
  1600. p = Popen(['whoami'], stdout=subprocess.PIPE)
  1601. s = p.stdout.read()
  1602. p.wait()
  1603. user = s.strip()
  1604. if type(user) is bytes:
  1605. user = decode(user)
  1606. except:
  1607. pass
  1608. if not user:
  1609. user = "user_%d" % os.getuid()
  1610. return user
  1611. class Parameters(object):
  1612. """Structure to hold standard part of command line parameters"""
  1613. # we don't need to define any methods
  1614. # pylint: disable=R0903
  1615. def __init__(self):
  1616. self.grass_gui = None
  1617. self.create_new = None
  1618. self.exit_grass = None
  1619. self.force_gislock_removal = None
  1620. self.mapset = None
  1621. self.geofile = None
  1622. self.tmp_location = False
  1623. def parse_cmdline(argv, default_gui):
  1624. """Parse the standard part of command line parameters"""
  1625. params = Parameters()
  1626. args = []
  1627. for i in argv:
  1628. # Check if the user asked for the version
  1629. if i in ["-v", "--version"]:
  1630. message("GRASS GIS %s" % GRASS_VERSION)
  1631. message('\n' + readfile(gpath("etc", "license")))
  1632. sys.exit()
  1633. # Check if the user asked for help
  1634. elif i in ["help", "-h", "-help", "--help", "--h"]:
  1635. help_message(default_gui=default_gui)
  1636. sys.exit()
  1637. # Check if the --text flag was given
  1638. elif i in ["-text", "--text"]:
  1639. params.grass_gui = 'text'
  1640. # Check if the --gtext flag was given
  1641. elif i in ["-gtext", "--gtext"]:
  1642. params.grass_gui = 'gtext'
  1643. # Check if the --gui flag was given
  1644. elif i in ["-gui", "--gui"]:
  1645. params.grass_gui = default_gui
  1646. # Check if the -wxpython flag was given
  1647. elif i in ["-wxpython", "-wx", "--wxpython", "--wx"]:
  1648. params.grass_gui = 'wxpython'
  1649. # Check if the user wants to create a new mapset
  1650. elif i == "-c":
  1651. params.create_new = True
  1652. elif i == "-e":
  1653. params.exit_grass = True
  1654. elif i == "-f":
  1655. params.force_gislock_removal = True
  1656. elif i == "--config":
  1657. print_params()
  1658. sys.exit()
  1659. elif i == "--tmp-location":
  1660. params.tmp_location = True
  1661. else:
  1662. args.append(i)
  1663. if len(args) > 1:
  1664. params.mapset = args[1]
  1665. params.geofile = args[0]
  1666. elif len(args) == 1:
  1667. if params.tmp_location:
  1668. params.geofile = args[0]
  1669. else:
  1670. params.mapset = args[0]
  1671. else:
  1672. params.mapset = None
  1673. return params
  1674. def validate_cmdline(params):
  1675. """ Validate the cmdline params and exit if necessary. """
  1676. if params.exit_grass and not params.create_new:
  1677. fatal(_("Flag -e requires also flag -c"))
  1678. if params.tmp_location and not params.geofile:
  1679. fatal(
  1680. _(
  1681. "Coordinate reference system argument (e.g. EPSG)"
  1682. " is needed for --tmp-location"
  1683. )
  1684. )
  1685. if params.tmp_location and params.mapset:
  1686. fatal(
  1687. _(
  1688. "Only one argument (e.g. EPSG) is needed for"
  1689. " --tmp-location, mapset name <{}> provided"
  1690. ).format(params.mapset)
  1691. )
  1692. def main():
  1693. """The main function which does the whole setup and run procedure
  1694. Only few things are set on the module level.
  1695. """
  1696. # Set language
  1697. # This has to be called before any _() function call!
  1698. # Subsequent functions are using _() calls and
  1699. # thus must be called only after Language has been set.
  1700. grass_config_dir = get_grass_config_dir()
  1701. set_language(grass_config_dir)
  1702. # Set default GUI
  1703. default_gui = "wxpython"
  1704. # explain what is happening in debug mode (visible only in debug mode)
  1705. debug("GRASS_DEBUG environmental variable is set. It is meant to be"
  1706. " an internal variable for debugging only this script.\n"
  1707. " Use 'g.gisenv set=\"DEBUG=[0-5]\"'"
  1708. " to turn GRASS GIS debug mode on if you wish to do so.")
  1709. # Set GRASS version number for R interface etc
  1710. # (must be an env var for MS Windows)
  1711. os.environ['GRASS_VERSION'] = GRASS_VERSION
  1712. # Set the GIS_LOCK variable to current process id
  1713. gis_lock = str(os.getpid())
  1714. os.environ['GIS_LOCK'] = gis_lock
  1715. batch_job = get_batch_job_from_env_variable()
  1716. # Parse the command-line options and set several global variables
  1717. batch_exec_param = '--exec'
  1718. try:
  1719. # raises ValueError when not found
  1720. index = sys.argv.index(batch_exec_param)
  1721. batch_job = sys.argv[index + 1:]
  1722. clean_argv = sys.argv[1:index]
  1723. params = parse_cmdline(clean_argv, default_gui=default_gui)
  1724. except ValueError:
  1725. params = parse_cmdline(sys.argv[1:], default_gui=default_gui)
  1726. validate_cmdline(params)
  1727. # For now, we allow, but not advertise/document, --tmp-location
  1728. # without --exec (usefulness to be evaluated).
  1729. grass_gui = params.grass_gui # put it to variable, it is used a lot
  1730. # TODO: with --tmp-location there is no point in loading settings
  1731. # i.e. rc file from home dir, but the code is too spread out
  1732. # to disable it at this point
  1733. gisrcrc = get_gisrc_from_config_dir(grass_config_dir, batch_job)
  1734. # Set the username
  1735. user = get_username()
  1736. # Set shell (needs to be called before load_env())
  1737. sh, shellname = get_shell()
  1738. grass_env_file = get_grass_env_file(sh, grass_config_dir)
  1739. # Load environmental variables from the file (needs to be called
  1740. # before create_tmp())
  1741. load_env(grass_env_file)
  1742. # Create the temporary directory and session grassrc file
  1743. tmpdir = create_tmp(user, gis_lock)
  1744. # Remove the tmpdir
  1745. # The removal will be executed when the python process terminates.
  1746. atexit.register(lambda: shutil.rmtree(tmpdir, ignore_errors=True))
  1747. # Create the session grassrc file
  1748. gisrc = create_gisrc(tmpdir, gisrcrc)
  1749. ensure_home()
  1750. # Set PATH, PYTHONPATH, ...
  1751. set_paths(grass_config_dir=grass_config_dir)
  1752. # Set GRASS_PAGER, GRASS_PYTHON, GRASS_GNUPLOT, GRASS_PROJSHARE
  1753. set_defaults()
  1754. set_display_defaults()
  1755. # Set GRASS_HTML_BROWSER
  1756. set_browser()
  1757. # First time user - GISRC is defined in the GRASS script
  1758. if not os.access(gisrc, os.F_OK):
  1759. if grass_gui == 'text' and not params.mapset:
  1760. fatal(_("Unable to start GRASS GIS. You have the choice to:\n"
  1761. " - Launch the graphical user interface with"
  1762. " the '--gui' switch\n"
  1763. " {cmd_name} --gui\n"
  1764. " - Launch with path to "
  1765. "the location/mapset as an argument\n"
  1766. " {cmd_name} /path/to/location/mapset`\n"
  1767. " - Create a location with '-c' and launch in its"
  1768. " PERMANENT mapset\n"
  1769. " {cmd_name} -c EPSG:number /path/to/location\n"
  1770. " {cmd_name} -c geofile /path/to/location\n"
  1771. " - Create manually the GISRC file ({gisrcrc})\n"
  1772. " - Use '--help' for further options\n"
  1773. " {cmd_name} --help\n"
  1774. "See also: https://grass.osgeo.org/{cmd_name}/manuals/helptext.html").format(
  1775. cmd_name=CMD_NAME, gisrcrc=gisrcrc))
  1776. create_initial_gisrc(gisrc)
  1777. message(_("Starting GRASS GIS..."))
  1778. # Ensure GUI is set
  1779. if batch_job or params.exit_grass:
  1780. grass_gui = 'text'
  1781. else:
  1782. if not grass_gui:
  1783. # if GUI was not set previously (e.g. command line),
  1784. # get it from rc file or env variable
  1785. grass_gui = read_gui(gisrc, default_gui)
  1786. # check that the GUI works but only if not doing a batch job
  1787. grass_gui = check_gui(expected_gui=grass_gui)
  1788. # save GUI only if we are not doibg batch job
  1789. save_gui(gisrc, grass_gui)
  1790. # Parsing argument to get LOCATION
  1791. if not params.mapset and not params.tmp_location:
  1792. # Try interactive startup
  1793. # User selects LOCATION and MAPSET if not set
  1794. if not set_mapset_interactive(grass_gui):
  1795. # No GUI available, update gisrc file
  1796. fatal(_("<{0}> requested, but not available. Run GRASS in text "
  1797. "mode (--text) or install missing package (usually "
  1798. "'grass-gui').").format(grass_gui))
  1799. else:
  1800. # Try non-interactive start up
  1801. if params.tmp_location:
  1802. # tmp loc requires other things to be set as well
  1803. set_mapset(gisrc=gisrc, geofile=params.geofile,
  1804. create_new=True,
  1805. tmp_location=params.tmp_location, tmpdir=tmpdir)
  1806. elif params.create_new and params.geofile:
  1807. set_mapset(gisrc=gisrc, arg=params.mapset,
  1808. geofile=params.geofile, create_new=True)
  1809. else:
  1810. set_mapset(gisrc=gisrc, arg=params.mapset,
  1811. create_new=params.create_new)
  1812. # Set GISDBASE, LOCATION_NAME, MAPSET, LOCATION from $GISRC
  1813. # e.g. wxGUI startup screen writes to the gisrc file,
  1814. # so loading it is the only universal way to obtain the values
  1815. # this suppose that both programs share the right path to gisrc file
  1816. # TODO: perhaps gisrcrc should be removed from here
  1817. # alternatively, we can check validity here with all the info we have
  1818. # about what was used to create gisrc
  1819. mapset_settings = load_gisrc(gisrc, gisrcrc=gisrcrc)
  1820. location = mapset_settings.full_mapset
  1821. # check and create .gislock file
  1822. lock_mapset(mapset_settings.full_mapset, user=user,
  1823. force_gislock_removal=params.force_gislock_removal,
  1824. grass_gui=grass_gui)
  1825. # unlock the mapset which is current at the time of turning off
  1826. # in case mapset was changed
  1827. atexit.register(lambda: unlock_gisrc_mapset(gisrc, gisrcrc))
  1828. # We now own the mapset (set and lock), so we can clean temporary
  1829. # files which previous session may have left behind. We do it even
  1830. # for first time user because the cost is low and first time user
  1831. # doesn't necessarily mean that the mapset is used for the first time.
  1832. clean_temp()
  1833. # build user fontcap if specified but not present
  1834. make_fontcap()
  1835. # TODO: is this really needed? Modules should call this when/if required.
  1836. ensure_db_connected(location)
  1837. # Display the version and license info
  1838. # only non-error, interactive version continues from here
  1839. if batch_job:
  1840. returncode = run_batch_job(batch_job)
  1841. clean_all()
  1842. sys.exit(returncode)
  1843. elif params.exit_grass:
  1844. # clean always at exit, cleans whatever is current mapset based on
  1845. # the GISRC env variable
  1846. clean_all()
  1847. sys.exit(0)
  1848. else:
  1849. show_banner()
  1850. say_hello()
  1851. show_info(shellname=shellname,
  1852. grass_gui=grass_gui, default_gui=default_gui)
  1853. if grass_gui == "wxpython":
  1854. message(_("Launching <%s> GUI in the background, please wait...")
  1855. % grass_gui)
  1856. if sh in ['csh', 'tcsh']:
  1857. shell_process = csh_startup(mapset_settings.full_mapset,
  1858. mapset_settings.location,
  1859. mapset_settings.mapset,
  1860. grass_env_file)
  1861. elif sh in ['bash', 'msh', 'cygwin']:
  1862. shell_process = bash_startup(mapset_settings.full_mapset,
  1863. mapset_settings.location,
  1864. grass_env_file)
  1865. else:
  1866. shell_process = default_startup(mapset_settings.full_mapset,
  1867. mapset_settings.location)
  1868. # start GUI and register shell PID in rc file
  1869. start_gui(grass_gui)
  1870. kv = read_gisrc(gisrc)
  1871. kv['PID'] = str(shell_process.pid)
  1872. write_gisrc(kv, gisrc)
  1873. exit_val = shell_process.wait()
  1874. if exit_val != 0:
  1875. warning(_("Failed to start shell '%s'") % os.getenv('SHELL'))
  1876. # close GUI if running
  1877. close_gui()
  1878. # here we are at the end of grass session
  1879. clean_all()
  1880. if not params.tmp_location:
  1881. writefile(gisrcrc, readfile(gisrc))
  1882. # After this point no more grass modules may be called
  1883. # done message at last: no atexit.register()
  1884. # or register done_message()
  1885. done_message()
  1886. if __name__ == '__main__':
  1887. main()