grass.py 82 KB

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