grass.py 67 KB

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