grass.py 64 KB

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