grass.py 90 KB

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