grass.py 70 KB

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