grass.py 67 KB

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