grass.py 88 KB

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