grass.py 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272
  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-2019 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 and len(os.getenv('GISBASE')) > 0:
  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 graphical welcome screen)"),
  302. text_detail=_("and set as default"),
  303. gtext=_("use text based interface (show graphical 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,svn_revision,version"),
  309. params=_("Parameters"),
  310. gisdbase=_("initial GRASS 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. # even so we set to 'xdg-open' as a generic fallback
  624. browser = "xdg-open"
  625. os.environ['GRASS_HTML_BROWSER'] = browser
  626. def ensure_home():
  627. """Set HOME if not set on MS Windows"""
  628. if windows and not os.getenv('HOME'):
  629. os.environ['HOME'] = os.path.join(os.getenv('HOMEDRIVE'),
  630. os.getenv('HOMEPATH'))
  631. def create_initial_gisrc(filename):
  632. # for convenience, define GISDBASE as pwd:
  633. s = r"""GISDBASE: %s
  634. LOCATION_NAME: <UNKNOWN>
  635. MAPSET: <UNKNOWN>
  636. """ % os.getcwd()
  637. writefile(filename, s)
  638. def check_gui(expected_gui):
  639. grass_gui = expected_gui
  640. # Check if we are running X windows by checking the DISPLAY variable
  641. if os.getenv('DISPLAY') or windows or macosx:
  642. # Check if python is working properly
  643. if expected_gui in ('wxpython', 'gtext'):
  644. nul = open(os.devnull, 'w')
  645. p = Popen([os.environ['GRASS_PYTHON']], stdin=subprocess.PIPE,
  646. stdout=nul, stderr=nul)
  647. nul.close()
  648. p.stdin.write("variable=True".encode(ENCODING))
  649. p.stdin.close()
  650. p.wait()
  651. msg = None
  652. if p.returncode != 0:
  653. # Python was not found - switch to text interface mode
  654. msg = _("The python command does not work as expected!\n"
  655. "Please check your GRASS_PYTHON environment variable.\n"
  656. "Use the -help option for details.\n")
  657. if not os.path.exists(wxpath("wxgui.py")):
  658. msg = _("GRASS GUI not found. Please check your installation.")
  659. if msg:
  660. warning(_("{}\nSwitching to text based interface mode.\n\n"
  661. "Hit RETURN to continue.\n").format(msg))
  662. sys.stdin.readline()
  663. grass_gui = 'text'
  664. else:
  665. # Display a message if a graphical interface was expected
  666. if expected_gui != 'text':
  667. # Set the interface mode to text
  668. warning(_("It appears that the X Windows system is not active.\n"
  669. "A graphical based user interface is not supported.\n"
  670. "(DISPLAY variable is not set.)\n"
  671. "Switching to text based interface mode.\n\n"
  672. "Hit RETURN to continue.\n"))
  673. sys.stdin.readline()
  674. grass_gui = 'text'
  675. return grass_gui
  676. def save_gui(gisrc, grass_gui):
  677. """Save the user interface variable in the grassrc file"""
  678. if os.access(gisrc, os.F_OK):
  679. kv = read_gisrc(gisrc)
  680. kv['GUI'] = grass_gui
  681. write_gisrc(kv, gisrc)
  682. def create_location(gisdbase, location, geostring):
  683. """Create GRASS Location using georeferenced file or EPSG
  684. EPSG code format is ``EPSG:code`` or ``EPSG:code:datum_trans``.
  685. :param gisdbase: Path to GRASS GIS database directory
  686. :param location: name of new Location
  687. :param geostring: path to a georeferenced file or EPSG code
  688. """
  689. if gpath('etc', 'python') not in sys.path:
  690. sys.path.append(gpath('etc', 'python'))
  691. from grass.script import core as gcore # pylint: disable=E0611
  692. try:
  693. if geostring and geostring.upper().find('EPSG:') > -1:
  694. # create location using EPSG code
  695. epsg = geostring.split(':', 1)[1]
  696. if ':' in epsg:
  697. epsg, datum_trans = epsg.split(':', 1)
  698. else:
  699. datum_trans = None
  700. gcore.create_location(gisdbase, location,
  701. epsg=epsg, datum_trans=datum_trans)
  702. elif geostring == 'XY':
  703. # create an XY location
  704. gcore.create_location(gisdbase, location)
  705. else:
  706. # create location using georeferenced file
  707. gcore.create_location(gisdbase, location,
  708. filename=geostring)
  709. except gcore.ScriptError as err:
  710. fatal(err.value.strip('"').strip("'").replace('\\n', os.linesep))
  711. # TODO: distinguish between valid for getting maps and usable as current
  712. # https://lists.osgeo.org/pipermail/grass-dev/2016-September/082317.html
  713. # interface created according to the current usage
  714. def is_mapset_valid(full_mapset):
  715. """Return True if GRASS Mapset is valid"""
  716. # WIND is created from DEFAULT_WIND by `g.region -d` and functions
  717. # or modules which create a new mapset. Most modules will fail if
  718. # WIND doesn't exist (assuming that neither GRASS_REGION nor
  719. # WIND_OVERRIDE environmental variables are set).
  720. return os.access(os.path.join(full_mapset, "WIND"), os.R_OK)
  721. def is_location_valid(gisdbase, location):
  722. """Return True if GRASS Location is valid
  723. :param gisdbase: Path to GRASS GIS database directory
  724. :param location: name of a Location
  725. """
  726. # DEFAULT_WIND file should not be required until you do something
  727. # that actually uses them. The check is just a heuristic; a directory
  728. # containing a PERMANENT/DEFAULT_WIND file is probably a GRASS
  729. # location, while a directory lacking it probably isn't.
  730. return os.access(os.path.join(gisdbase, location,
  731. "PERMANENT", "DEFAULT_WIND"), os.F_OK)
  732. # basically checking location, possibly split into two functions
  733. # (mapset one can call location one)
  734. def get_mapset_invalid_reason(gisdbase, location, mapset):
  735. """Returns a message describing what is wrong with the Mapset
  736. The goal is to provide the most suitable error message
  737. (rather than to do a quick check).
  738. :param gisdbase: Path to GRASS GIS database directory
  739. :param location: name of a Location
  740. :param mapset: name of a Mapset
  741. :returns: translated message
  742. """
  743. full_location = os.path.join(gisdbase, location)
  744. full_permanent = os.path.join(full_location, 'PERMANENT')
  745. full_mapset = os.path.join(full_location, mapset)
  746. # first checking the location validity
  747. if not os.path.exists(full_location):
  748. return _("Location <%s> doesn't exist") % full_location
  749. elif 'PERMANENT' not in os.listdir(full_location):
  750. return _("<%s> is not a valid GRASS Location"
  751. " because PERMANENT Mapset is missing") % full_location
  752. elif not os.path.isdir(full_permanent):
  753. return _("<%s> is not a valid GRASS Location"
  754. " because PERMANENT is not a directory") % full_location
  755. # partially based on the is_location_valid() function
  756. elif not os.path.isfile(os.path.join(full_permanent,
  757. 'DEFAULT_WIND')):
  758. return _("<%s> is not a valid GRASS Location"
  759. " because PERMANENT Mapset does not have a DEFAULT_WIND file"
  760. " (default computational region)") % full_location
  761. # if location is valid, check mapset
  762. elif mapset not in os.listdir(full_location):
  763. return _("Mapset <{mapset}> doesn't exist in GRASS Location <{loc}>. "
  764. "A new mapset can be created by '-c' switch.").format(
  765. mapset=mapset, loc=location)
  766. elif not os.path.isdir(full_mapset):
  767. return _("<%s> is not a GRASS Mapset"
  768. " because it is not a directory") % mapset
  769. elif not os.path.isfile(os.path.join(full_mapset, 'WIND')):
  770. return _("<%s> is not a valid GRASS Mapset"
  771. " because it does not have a WIND file") % mapset
  772. # based on the is_mapset_valid() function
  773. elif not os.access(os.path.join(full_mapset, "WIND"), os.R_OK):
  774. return _("<%s> is not a valid GRASS Mapset"
  775. " because its WIND file is not readable") % mapset
  776. else:
  777. return _("Mapset <{mapset}> or Location <{location}> is"
  778. " invalid for an unknown reason").format(
  779. mapset=mapset, loc=location)
  780. def can_create_location(gisdbase, location):
  781. """Checks if location can be created"""
  782. path = os.path.join(gisdbase, location)
  783. if os.path.exists(path):
  784. return False
  785. return True
  786. def cannot_create_location_reason(gisdbase, location):
  787. """Returns a message describing why location cannot be created
  788. The goal is to provide the most suitable error message
  789. (rather than to do a quick check).
  790. :param gisdbase: Path to GRASS GIS database directory
  791. :param location: name of a Location
  792. :returns: translated message
  793. """
  794. path = os.path.join(gisdbase, location)
  795. if is_location_valid(gisdbase, location):
  796. return _("Unable to create new location because"
  797. " the location <{location}>"
  798. " already exists.").format(**locals())
  799. elif os.path.isfile(path):
  800. return _("Unable to create new location <{location}> because"
  801. " <{path}> is a file.").format(**locals())
  802. elif os.path.isdir(path):
  803. return _("Unable to create new location <{location}> because"
  804. " the directory <{path}>"
  805. " already exists.").format(**locals())
  806. else:
  807. return _("Unable to create new location in"
  808. " the directory <{path}>"
  809. " for an unknown reason.").format(**locals())
  810. def set_mapset(gisrc, arg=None, geofile=None, create_new=False,
  811. tmp_location=False, tmpdir=None):
  812. """Selected Location and Mapset are checked and created if requested
  813. The gisrc (GRASS environment file) is written at the end
  814. (nothing is returned).
  815. tmp_location requires tmpdir (which is used as gisdbase)
  816. """
  817. # TODO: arg param seems to be always the mapset parameter (or a dash
  818. # in a distant past), refactor
  819. l = arg
  820. if l:
  821. if l == '.':
  822. l = os.getcwd()
  823. elif not os.path.isabs(l):
  824. l = os.path.abspath(l)
  825. l, mapset = os.path.split(l)
  826. if not mapset:
  827. l, mapset = os.path.split(l)
  828. l, location_name = os.path.split(l)
  829. gisdbase = l
  830. # all was None for tmp loc so that case goes here quickly
  831. # TODO: but the above code needs review anyway
  832. if tmp_location:
  833. # set gisdbase to temporary directory
  834. gisdbase = tmpdir
  835. # we are already in a unique directory, so we can use fixed name
  836. location_name = "tmploc"
  837. # we need only one mapset
  838. mapset = "PERMANENT"
  839. debug("Using temporary location <{gdb}{sep}{lc}>".format(
  840. gdb=gisdbase, lc=location_name, sep=os.path.sep))
  841. if gisdbase and location_name and mapset:
  842. path = os.path.join(gisdbase, location_name, mapset)
  843. # check if 'path' is a valid GRASS location/mapset
  844. path_is_valid_mapset = is_mapset_valid(path)
  845. if path_is_valid_mapset and create_new:
  846. warning(_("Mapset <{}> already exists. Ignoring the"
  847. " request to create it. Note that this warning"
  848. " may become an error in future versions.")
  849. .format(path))
  850. if not path_is_valid_mapset:
  851. if not create_new:
  852. # 'path' is not a valid mapset and user does not
  853. # want to create anything new
  854. fatal(get_mapset_invalid_reason(gisdbase, location_name, mapset))
  855. else:
  856. # 'path' is not valid and the user wants to create
  857. # mapset on the fly
  858. # check if 'location_name' is a valid GRASS location
  859. if not is_location_valid(gisdbase, location_name):
  860. if not tmp_location:
  861. # 'location_name' is not a valid GRASS location
  862. # and user requested its creation, so we parsed
  863. # the path wrong and need to move one level
  864. # and use 'PERMANENT' mapset
  865. # (we already got that right in case of tmploc)
  866. gisdbase = os.path.join(gisdbase, location_name)
  867. location_name = mapset
  868. mapset = "PERMANENT"
  869. if not can_create_location(gisdbase, location_name):
  870. fatal(cannot_create_location_reason(
  871. gisdbase, location_name))
  872. # create new location based on the provided EPSG/...
  873. message(_("Creating new GRASS GIS location <{}>...")
  874. .format(location_name))
  875. create_location(gisdbase, location_name, geofile)
  876. else:
  877. # 'location_name' is a valid GRASS location,
  878. # create new mapset
  879. message(_("Creating new GRASS GIS mapset <{}>...")
  880. .format(mapset))
  881. if os.path.isfile(path):
  882. # not a valid mapset, but dir exists, assuming
  883. # broken/incomplete mapset
  884. fatal(_("Unable to create new mapset <{mapset}>"
  885. " because <{path}> is a file.")
  886. .format(mapset=mapset, path=path))
  887. elif os.path.isdir(path):
  888. # not a valid mapset, but dir exists, assuming
  889. # broken/incomplete mapset
  890. warning(_("The mapset <{}> is missing the WIND file"
  891. " (computational region). It will be"
  892. " fixed now. Note that this warning"
  893. " may become an error in future versions.")
  894. .format(mapset))
  895. else:
  896. # create mapset directory
  897. os.mkdir(path)
  898. # make directory a mapset, add the region
  899. # copy PERMANENT/DEFAULT_WIND to <mapset>/WIND
  900. s = readfile(os.path.join(gisdbase, location_name,
  901. "PERMANENT", "DEFAULT_WIND"))
  902. writefile(os.path.join(path, "WIND"), s)
  903. if os.access(gisrc, os.R_OK):
  904. kv = read_gisrc(gisrc)
  905. else:
  906. kv = {}
  907. kv['GISDBASE'] = gisdbase
  908. kv['LOCATION_NAME'] = location_name
  909. kv['MAPSET'] = mapset
  910. write_gisrc(kv, gisrc)
  911. else:
  912. fatal(_("GRASS GIS database directory, location and mapset"
  913. " not set properly."
  914. " Use GUI or command line to set them."))
  915. def set_mapset_interactive(grass_gui):
  916. """User selects Location and Mapset in an interative way
  917. The gisrc (GRASS environment file) is written at the end.
  918. """
  919. if not os.path.exists(wxpath("gis_set.py")) and grass_gui != 'text':
  920. debug("No GUI available, switching to text mode")
  921. return False
  922. # Check for text interface
  923. if grass_gui == 'text':
  924. # TODO: maybe this should be removed and solved from outside
  925. # this depends on what we expect from this function
  926. # should gisrc be ok after running or is it allowed to be still not set
  927. pass
  928. # Check for GUI
  929. elif grass_gui in ('gtext', 'wxpython'):
  930. gui_startup(grass_gui)
  931. else:
  932. # Shouldn't need this but you never know
  933. fatal(_("Invalid user interface specified - <%s>. "
  934. "Use the --help option to see valid interface names.") % grass_gui)
  935. return True
  936. def gui_startup(grass_gui):
  937. """Start GUI for startup (setting gisrc file)"""
  938. if grass_gui in ('wxpython', 'gtext'):
  939. ret = call([os.getenv('GRASS_PYTHON'), wxpath("gis_set.py")])
  940. # this if could be simplified to three branches (0, 5, rest)
  941. # if there is no need to handle unknown code separately
  942. if ret == 0:
  943. pass
  944. elif ret in [1, 2]:
  945. # 1 probably error coming from gis_set.py
  946. # 2 probably file not found from python interpreter
  947. # formerly we were starting in text mode instead, now we just fail
  948. # which is more straightforward for everybody
  949. fatal(_("Error in GUI startup. See messages above (if any)"
  950. " and if necessary, please"
  951. " report this error to the GRASS developers.\n"
  952. "On systems with package manager, make sure you have the right"
  953. " GUI package, probably named grass-gui, installed.\n"
  954. "To run GRASS GIS in text mode use the --text flag.\n"
  955. "Use '--help' for further options\n"
  956. " {cmd_name} --help\n"
  957. "See also: https://grass.osgeo.org/{cmd_name}/manuals/helptext.html").format(
  958. cmd_name=cmd_name))
  959. elif ret == 5: # defined in gui/wxpython/gis_set.py
  960. # User wants to exit from GRASS
  961. message(_("Exit was requested in GUI.\nGRASS GIS will not start. Bye."))
  962. sys.exit(0)
  963. else:
  964. fatal(_("Invalid return code from GUI startup script.\n"
  965. "Please advise GRASS developers of this error."))
  966. # we don't follow the LOCATION_NAME legacy naming here but we have to still
  967. # translate to it, so always double check
  968. class MapsetSettings(object):
  969. """Holds GRASS GIS database directory, Location and Mapset
  970. Provides few convenient functions.
  971. """
  972. def __init__(self):
  973. self.gisdbase = None
  974. self.location = None
  975. self.mapset = None
  976. self._full_mapset = None
  977. # TODO: perhaps full_mapset would be better as mapset_path
  978. # TODO: works only when set for the first time
  979. # this follows the current usage but we must invalidate when
  980. # the others are changed (use properties for that)
  981. @property
  982. def full_mapset(self):
  983. if self._full_mapset is None:
  984. self._full_mapset = os.path.join(self.gisdbase, self.location,
  985. self.mapset)
  986. return self._full_mapset
  987. # TODO: perhaps conversion to bool would be nicer
  988. def is_valid(self):
  989. return self.gisdbase and self.location and self.mapset
  990. # TODO: does it really makes sense to tell user about gisrcrc?
  991. # anything could have happened in between loading from gisrcrc and now
  992. # (we do e.g. GUI or creating loctation)
  993. def load_gisrc(gisrc, gisrcrc):
  994. """Get the settings of Location and Mapset from the gisrc file
  995. :returns: MapsetSettings object
  996. """
  997. mapset_settings = MapsetSettings()
  998. kv = read_gisrc(gisrc)
  999. mapset_settings.gisdbase = kv.get('GISDBASE')
  1000. mapset_settings.location = kv.get('LOCATION_NAME')
  1001. mapset_settings.mapset = kv.get('MAPSET')
  1002. if not mapset_settings.is_valid():
  1003. fatal(_("Error reading data path information from g.gisenv.\n"
  1004. "GISDBASE={gisbase}\n"
  1005. "LOCATION_NAME={location}\n"
  1006. "MAPSET={mapset}\n\n"
  1007. "Check the <{file}> file.").format(
  1008. gisbase=mapset_settings.gisdbase,
  1009. location=mapset_settings.location,
  1010. mapset=mapset_settings.mapset,
  1011. file=gisrcrc))
  1012. return mapset_settings
  1013. # load environmental variables from grass_env_file
  1014. def load_env(grass_env_file):
  1015. if not os.access(grass_env_file, os.R_OK):
  1016. return
  1017. for line in readfile(grass_env_file).split(os.linesep):
  1018. try:
  1019. k, v = map(lambda x: x.strip(), line.strip().split(' ', 1)[1].split('=', 1))
  1020. except:
  1021. continue
  1022. debug("Environmental variable set {0}={1}".format(k, v))
  1023. os.environ[k] = v
  1024. # Allow for mixed ISIS-GRASS Environment
  1025. if os.getenv('ISISROOT'):
  1026. isis = os.getenv('ISISROOT')
  1027. os.environ['ISIS_LIB'] = isis + os.sep + "lib"
  1028. os.environ['ISIS_3RDPARTY'] = isis + os.sep + "3rdParty" + os.sep + "lib"
  1029. os.environ['QT_PLUGIN_PATH'] = isis + os.sep + "3rdParty" + os.sep + "plugins"
  1030. # os.environ['ISIS3DATA'] = isis + "$ISIS3DATA"
  1031. libpath = os.getenv('LD_LIBRARY_PATH', '')
  1032. isislibpath = os.getenv('ISIS_LIB')
  1033. isis3rdparty = os.getenv('ISIS_3RDPARTY')
  1034. os.environ['LD_LIBRARY_PATH'] = libpath + os.pathsep + isislibpath + os.pathsep + isis3rdparty
  1035. def set_language(grass_config_dir):
  1036. # This function is used to override system default language and locale
  1037. # Such override can be requested only from wxGUI
  1038. # An override if user has provided correct environmental variables as
  1039. # LC_MESSAGES or LANG is not necessary.
  1040. # Unfortunately currently a working solution for Windows is lacking
  1041. # thus it always on Vista and XP will print an error.
  1042. # See discussion for Windows not following its own documentation and
  1043. # not accepting ISO codes as valid locale identifiers http://bugs.python.org/issue10466
  1044. language = 'None' # Such string sometimes is present in wx file
  1045. encoding = None
  1046. # Override value is stored in wxGUI preferences file.
  1047. # As it's the only thing required, we'll just grep it out.
  1048. try:
  1049. fd = open(os.path.join(grass_config_dir, 'wx'), 'r')
  1050. except:
  1051. # Even if there is no override, we still need to set locale.
  1052. pass
  1053. else:
  1054. for line in fd:
  1055. if re.search('^language', line):
  1056. line = line.rstrip(' %s' % os.linesep)
  1057. language = ''.join(line.split(';')[-1:])
  1058. break
  1059. fd.close()
  1060. # Backwards compatibility with old wx preferences files
  1061. if language == 'C':
  1062. language = 'en'
  1063. if language == 'None' or language == '' or not language:
  1064. # Language override is disabled (system language specified)
  1065. # As by default program runs with C locale, but users expect to
  1066. # have their default locale, we'll just set default locale
  1067. try:
  1068. locale.setlocale(locale.LC_ALL, '')
  1069. except locale.Error as e:
  1070. # If we get here, system locale settings are terribly wrong
  1071. # There is no point to continue as GRASS/Python will fail
  1072. # in some other unpredictable way.
  1073. sys.stderr.write(
  1074. "System locale is not usable (LC_ALL variable not defined)."
  1075. " Most likely it indicates misconfigured environment.\n")
  1076. sys.stderr.write("Reported error message: %s\n" % e)
  1077. # it would be too drastic to exit
  1078. # sys.exit("Fix system locale settings and then try again.")
  1079. locale.setlocale(locale.LC_ALL, 'C')
  1080. sys.stderr.write("Default locale settings are missing. GRASS running with C locale.")
  1081. language, encoding = locale.getdefaultlocale()
  1082. if not language:
  1083. sys.stderr.write("Default locale settings are missing. GRASS running with C locale.")
  1084. return
  1085. else:
  1086. debug("A language override has been requested."
  1087. " Trying to switch GRASS into '%s'..." % language)
  1088. try:
  1089. locale.setlocale(locale.LC_ALL, language)
  1090. except locale.Error as e:
  1091. try:
  1092. # Locale lang.encoding might be missing. Let's try
  1093. # UTF-8 encoding before giving up as on Linux systems
  1094. # lang.UTF-8 locales are more common than legacy
  1095. # ISO-8859 ones.
  1096. encoding = 'UTF-8'
  1097. normalized = locale.normalize('%s.%s' % (language, encoding))
  1098. locale.setlocale(locale.LC_ALL, normalized)
  1099. except locale.Error as e:
  1100. if language == 'en':
  1101. # A workaround for Python Issue30755
  1102. # https://bugs.python.org/issue30755
  1103. if locale.normalize('C.UTF-8') == 'en_US.UTF-8':
  1104. locale.setlocale(locale.LC_ALL, 'C')
  1105. os.environ['LANGUAGE'] = 'C'
  1106. os.environ['LANG'] = 'C'
  1107. os.environ['LC_MESSAGES'] = 'C'
  1108. os.environ['LC_NUMERIC'] = 'C'
  1109. os.environ['LC_TIME'] = 'C'
  1110. sys.stderr.write(
  1111. "To avoid Unicode errors in GUI, install"
  1112. " en_US.UTF-8 locale and restart GRASS.\n"
  1113. "Also consider upgrading your Python version"
  1114. " to one containing fix for Python Issue 30755.\n")
  1115. return
  1116. # en_US locale might be missing, still all messages in
  1117. # GRASS are already in en_US language.
  1118. # Using plain C as locale forces encodings to ascii
  1119. # thus lets try our luck with C.UTF-8 first.
  1120. # See bugs #3441 and #3423
  1121. try:
  1122. locale.setlocale(locale.LC_ALL, 'C.UTF-8')
  1123. except locale.Error as e:
  1124. # All lost. Setting to C as much as possible.
  1125. # We can not call locale.normalize on C as it
  1126. # will transform it to en_US and we already know
  1127. # it doesn't work.
  1128. locale.setlocale(locale.LC_ALL, 'C')
  1129. os.environ['LANGUAGE'] = 'C'
  1130. os.environ['LANG'] = 'C'
  1131. os.environ['LC_MESSAGES'] = 'C'
  1132. os.environ['LC_NUMERIC'] = 'C'
  1133. os.environ['LC_TIME'] = 'C'
  1134. gettext.install('grasslibs', gpath('locale'))
  1135. sys.stderr.write(
  1136. "All attempts to enable English language have"
  1137. " failed. GRASS running with C locale.\n"
  1138. "If you observe UnicodeError in Python,"
  1139. " install en_US.UTF-8"
  1140. " locale and restart GRASS.\n")
  1141. return
  1142. else:
  1143. # The last attempt...
  1144. try:
  1145. encoding = locale.getpreferredencoding()
  1146. normalized = locale.normalize('%s.%s' % (language, encoding))
  1147. locale.setlocale(locale.LC_ALL, normalized)
  1148. except locale.Error as e:
  1149. # If we got so far, attempts to set up language and locale have failed
  1150. # on this system
  1151. sys.stderr.write("Failed to enforce user specified language '%s' with error: '%s'\n" % (language, e))
  1152. sys.stderr.write("A LANGUAGE environmental variable has been set.\nPart of messages will be displayed in the requested language.\n")
  1153. # Even if setting locale will fail, let's set LANG in a hope,
  1154. # that UI will use it GRASS texts will be in selected language,
  1155. # system messages (i.e. OK, Cancel etc.) - in system default
  1156. # language
  1157. os.environ['LANGUAGE'] = language
  1158. os.environ['LANG'] = language
  1159. return
  1160. # Set up environment for subprocesses
  1161. os.environ['LANGUAGE'] = language
  1162. os.environ['LANG'] = language
  1163. if language == 'ko_KR' and encoding == 'cp949':
  1164. # The default encoding for the Korean language in Windows is cp949,
  1165. # Microsoft's proprietary extension to euc-kr, but gettext prints no
  1166. # translated messages at all in the Command Prompt window if LC_CTYPE
  1167. # is set to ko_KR.cp949. Here, force LC_CTYPE to be euc-kr.
  1168. normalized = 'euc-kr'
  1169. encoding = None
  1170. elif encoding:
  1171. normalized = locale.normalize('%s.%s' % (language, encoding))
  1172. else:
  1173. normalized = language
  1174. for lc in ('LC_CTYPE', 'LC_MESSAGES', 'LC_TIME', 'LC_COLLATE',
  1175. 'LC_MONETARY', 'LC_PAPER', 'LC_NAME', 'LC_ADDRESS',
  1176. 'LC_TELEPHONE', 'LC_MEASUREMENT', 'LC_IDENTIFICATION'):
  1177. os.environ[lc] = normalized
  1178. # Some code in GRASS might not like other decimal separators than .
  1179. # Other potential sources for problems are: LC_TIME LC_CTYPE
  1180. locale.setlocale(locale.LC_NUMERIC, 'C')
  1181. os.environ['LC_NUMERIC'] = 'C'
  1182. if os.getenv('LC_ALL'):
  1183. del os.environ['LC_ALL'] # Remove LC_ALL to not override LC_NUMERIC
  1184. # From now on enforce the new language
  1185. if encoding:
  1186. gettext.install('grasslibs', gpath('locale'), codeset=encoding)
  1187. else:
  1188. gettext.install('grasslibs', gpath('locale'))
  1189. # TODO: grass_gui parameter is a hack and should be removed, see below
  1190. def lock_mapset(mapset_path, force_gislock_removal, user, grass_gui):
  1191. """Lock the mapset and return name of the lock file
  1192. Behavior on error must be changed somehow; now it fatals but GUI case is
  1193. unresolved.
  1194. """
  1195. if not os.path.exists(mapset_path):
  1196. fatal(_("Path '%s' doesn't exist") % mapset_path)
  1197. if not os.access(mapset_path, os.W_OK):
  1198. error = _("Path '%s' not accessible.") % mapset_path
  1199. stat_info = os.stat(mapset_path)
  1200. mapset_uid = stat_info.st_uid
  1201. if mapset_uid != os.getuid():
  1202. # GTC %s is mapset's folder path
  1203. error = "%s\n%s" % (error, _("You are not the owner of '%s'.") % mapset_path)
  1204. fatal(error)
  1205. # Check for concurrent use
  1206. lockfile = os.path.join(mapset_path, ".gislock")
  1207. ret = call([gpath("etc", "lock"), lockfile, "%d" % os.getpid()])
  1208. msg = None
  1209. if ret == 2:
  1210. if not force_gislock_removal:
  1211. msg = _("%(user)s is currently running GRASS in selected mapset"
  1212. " (file %(file)s found). Concurrent use not allowed.\n"
  1213. "You can force launching GRASS using -f flag"
  1214. " (note that you need permission for this operation)."
  1215. " Have another look in the processor "
  1216. "manager just to be sure..." % {
  1217. 'user': user, 'file': lockfile})
  1218. else:
  1219. try_remove(lockfile)
  1220. message(_("%(user)s is currently running GRASS in selected mapset"
  1221. " (file %(file)s found). Forcing to launch GRASS..." % {
  1222. 'user': user, 'file': lockfile}))
  1223. elif ret != 0:
  1224. msg = _("Unable to properly access '%s'.\n"
  1225. "Please notify system personnel.") % lockfile
  1226. # TODO: the gui decision should be done by the caller
  1227. # this needs some change to the function interface, return tuple or
  1228. # use exceptions (better option)
  1229. if msg:
  1230. if grass_gui == "wxpython":
  1231. call([os.getenv('GRASS_PYTHON'), wxpath("gis_set_error.py"), msg])
  1232. # TODO: here we probably miss fatal or exit, needs to be added
  1233. else:
  1234. fatal(msg)
  1235. debug("Mapset <{mapset}> locked using '{lockfile}'".format(
  1236. mapset=mapset_path, lockfile=lockfile))
  1237. return lockfile
  1238. # TODO: the gisrcrc here does not make sense, remove it from load_gisrc
  1239. def unlock_gisrc_mapset(gisrc, gisrcrc):
  1240. """Unlock mapset from the gisrc file"""
  1241. settings = load_gisrc(gisrc, gisrcrc)
  1242. lockfile = os.path.join(settings.full_mapset, ".gislock")
  1243. # this fails silently, perhaps a warning would be helpful to
  1244. # catch cases when removal was not possible due to e.g. another
  1245. # session force-removing the file (unlocking the mapset)
  1246. try_remove(lockfile)
  1247. def make_fontcap():
  1248. # TODO: is GRASS_FONT_CAP ever defined? It seems it must be defined in system
  1249. fc = os.getenv('GRASS_FONT_CAP')
  1250. if fc and not os.access(fc, os.R_OK):
  1251. message(_("Building user fontcap..."))
  1252. call(["g.mkfontcap"])
  1253. def ensure_db_connected(mapset):
  1254. """Predefine default driver if DB connection not defined
  1255. :param mapset: full path to the mapset
  1256. """
  1257. if not os.access(os.path.join(mapset, "VAR"), os.F_OK):
  1258. call(['db.connect', '-c', '--quiet'])
  1259. def get_shell():
  1260. # set SHELL on ms windowns
  1261. # this was at the very beginning of the script but it can be anywhere
  1262. if windows:
  1263. if os.getenv('GRASS_SH'):
  1264. os.environ['SHELL'] = os.getenv('GRASS_SH')
  1265. if not os.getenv('SHELL'):
  1266. os.environ['SHELL'] = os.getenv('COMSPEC', 'cmd.exe')
  1267. # cygwin has many problems with the shell setup
  1268. # below, so i hardcoded everything here.
  1269. if sys.platform == 'cygwin':
  1270. sh = "cygwin"
  1271. shellname = "GNU Bash (Cygwin)"
  1272. os.environ['SHELL'] = "/usr/bin/bash.exe"
  1273. os.environ['OSTYPE'] = "cygwin"
  1274. else:
  1275. # in docker the 'SHELL' variable may not be
  1276. # visible in a Python session unless 'ENV SHELL /bin/bash' is set in Dockerfile
  1277. try:
  1278. sh = os.path.basename(os.getenv('SHELL'))
  1279. except:
  1280. sh = 'sh'
  1281. os.environ['SHELL'] = sh
  1282. if windows and sh:
  1283. sh = os.path.splitext(sh)[0]
  1284. if sh == "ksh":
  1285. shellname = "Korn Shell"
  1286. elif sh == "csh":
  1287. shellname = "C Shell"
  1288. elif sh == "tcsh":
  1289. shellname = "TC Shell"
  1290. elif sh == "bash":
  1291. shellname = "Bash Shell"
  1292. elif sh == "sh":
  1293. shellname = "Bourne Shell"
  1294. elif sh == "zsh":
  1295. shellname = "Z Shell"
  1296. elif sh == "cmd":
  1297. shellname = "Command Prompt"
  1298. elif sh == "powershell":
  1299. shellname = "Windows PowerShell"
  1300. else:
  1301. shellname = "shell"
  1302. # check for SHELL
  1303. if not os.getenv('SHELL'):
  1304. fatal(_("The SHELL variable is not set"))
  1305. return sh, shellname
  1306. def get_grass_env_file(sh, grass_config_dir):
  1307. """Get name of the shell-specific GRASS environment (rc) file"""
  1308. if sh in ['csh', 'tcsh']:
  1309. grass_env_file = os.path.join(grass_config_dir, 'cshrc')
  1310. elif sh in ['bash', 'msh', 'cygwin', 'sh']:
  1311. grass_env_file = os.path.join(grass_config_dir, 'bashrc')
  1312. elif sh == 'zsh':
  1313. grass_env_file = os.path.join(grass_config_dir, 'zshrc')
  1314. elif sh in ['cmd', 'powershell']:
  1315. grass_env_file = os.path.join(grass_config_dir, 'env.bat')
  1316. else:
  1317. grass_env_file = os.path.join(grass_config_dir, 'bashrc')
  1318. warning(_("Unsupported shell <{sh}>: {env_file}").format(
  1319. sh=sh, env_file=grass_env_file))
  1320. return grass_env_file
  1321. def get_batch_job_from_env_variable():
  1322. """Get script to execute from batch job variable if available
  1323. Fails with fatal if variable is set but content unusable.
  1324. """
  1325. # hack to process batch jobs:
  1326. batch_job = os.getenv('GRASS_BATCH_JOB')
  1327. # variable defined, but user might not have been careful enough
  1328. if batch_job:
  1329. if not os.access(batch_job, os.F_OK):
  1330. # wrong file
  1331. fatal(_("Job file <%s> has been defined in "
  1332. "the 'GRASS_BATCH_JOB' variable but not found. Exiting."
  1333. "\n\n"
  1334. "Use 'unset GRASS_BATCH_JOB' to disable "
  1335. "batch job processing.") % batch_job)
  1336. elif not os.access(batch_job, os.X_OK):
  1337. # right file, but ...
  1338. fatal(_("Change file permission to 'executable' for <%s>")
  1339. % batch_job)
  1340. return batch_job
  1341. def run_batch_job(batch_job):
  1342. """Runs script, module or any command
  1343. If *batch_job* is a string (insecure) shell=True is used for execution.
  1344. :param batch_job: executable and parameters in a list or a string
  1345. """
  1346. batch_job_string = batch_job
  1347. if not isinstance(batch_job, string_types):
  1348. # for messages only
  1349. batch_job_string = ' '.join(batch_job)
  1350. message(_("Executing <%s> ...") % batch_job_string)
  1351. if isinstance(batch_job, string_types):
  1352. # shell=True is keeping the original GRASS_BATCH_JOB behavior
  1353. def quote(string):
  1354. if '"' in string:
  1355. return "'%s'" % batch_job
  1356. else:
  1357. return '"%s"' % batch_job
  1358. batch_job = quote(batch_job)
  1359. proc = Popen(batch_job, shell=True)
  1360. else:
  1361. try:
  1362. proc = Popen(batch_job, shell=False)
  1363. except OSError as error:
  1364. fatal(_("Execution of <{cmd}> failed:\n"
  1365. "{error}").format(cmd=batch_job_string, error=error))
  1366. returncode = proc.wait()
  1367. message(_("Execution of <%s> finished.") % batch_job_string)
  1368. return returncode
  1369. def start_gui(grass_gui):
  1370. """Start specified GUI
  1371. :param grass_gui: GUI name (allowed values: 'wxpython')
  1372. """
  1373. # Start the chosen GUI but ignore text
  1374. debug("GRASS GUI should be <%s>" % grass_gui)
  1375. # Check for gui interface
  1376. if grass_gui == "wxpython":
  1377. Popen([os.getenv('GRASS_PYTHON'), wxpath("wxgui.py")])
  1378. def close_gui():
  1379. """Close GUI if running"""
  1380. if gpath('etc', 'python') not in sys.path:
  1381. sys.path.append(gpath('etc', 'python'))
  1382. from grass.script import core as gcore # pylint: disable=E0611
  1383. env = gcore.gisenv()
  1384. if 'GUI_PID' not in env:
  1385. return
  1386. import signal
  1387. for pid in env['GUI_PID'].split(','):
  1388. debug("Exiting GUI with pid={0}".format(pid))
  1389. try:
  1390. os.kill(int(pid), signal.SIGTERM)
  1391. except OSError as e:
  1392. message(_("Unable to close GUI. {0}").format(e))
  1393. def clear_screen():
  1394. """Clear terminal"""
  1395. if windows:
  1396. pass
  1397. # TODO: uncomment when PDCurses works.
  1398. # cls
  1399. else:
  1400. if not is_debug():
  1401. call(["tput", "clear"])
  1402. def show_banner():
  1403. """Write GRASS GIS ASCII name to stderr"""
  1404. sys.stderr.write(r"""
  1405. __________ ___ __________ _______________
  1406. / ____/ __ \/ | / ___/ ___/ / ____/ _/ ___/
  1407. / / __/ /_/ / /| | \__ \\_ \ / / __ / / \__ \
  1408. / /_/ / _, _/ ___ |___/ /__/ / / /_/ // / ___/ /
  1409. \____/_/ |_/_/ |_/____/____/ \____/___//____/
  1410. """)
  1411. def say_hello():
  1412. """Write welcome to stderr including Subversion revision if in svn copy"""
  1413. sys.stderr.write(_("Welcome to GRASS GIS %s") % grass_version)
  1414. if grass_version.endswith('svn'):
  1415. try:
  1416. filerev = open(gpath('etc', 'VERSIONNUMBER'))
  1417. linerev = filerev.readline().rstrip('\n')
  1418. filerev.close()
  1419. revision = linerev.split(' ')[1]
  1420. sys.stderr.write(' (' + revision + ')')
  1421. except:
  1422. pass
  1423. def show_info(shellname, grass_gui, default_gui):
  1424. """Write basic info about GRASS GIS and GRASS session to stderr"""
  1425. sys.stderr.write(
  1426. r"""
  1427. %-41shttps://grass.osgeo.org
  1428. %-41s%s (%s)
  1429. %-41sg.manual -i
  1430. %-41sg.version -c
  1431. %-41sg.version -x
  1432. """ % (_("GRASS GIS homepage:"),
  1433. # GTC Running through: SHELL NAME
  1434. _("This version running through:"),
  1435. shellname, os.getenv('SHELL'),
  1436. _("Help is available with the command:"),
  1437. _("See the licence terms with:"),
  1438. _("See citation options with:")))
  1439. if grass_gui == 'wxpython':
  1440. message("%-41sg.gui wxpython" % _("If required, restart the GUI with:"))
  1441. else:
  1442. message("%-41sg.gui %s" % (_("Start the GUI with:"), default_gui))
  1443. message("%-41sexit" % _("When ready to quit enter:"))
  1444. message("")
  1445. def csh_startup(location, location_name, mapset, grass_env_file):
  1446. userhome = os.getenv('HOME') # save original home
  1447. home = location
  1448. os.environ['HOME'] = home
  1449. cshrc = os.path.join(home, ".cshrc")
  1450. tcshrc = os.path.join(home, ".tcshrc")
  1451. try_remove(cshrc)
  1452. try_remove(tcshrc)
  1453. f = open(cshrc, 'w')
  1454. f.write("set home = %s\n" % userhome)
  1455. f.write("set history = 3000 savehist = 3000 noclobber ignoreeof\n")
  1456. f.write("set histfile = %s\n" % os.path.join(os.getenv('HOME'),
  1457. ".history"))
  1458. f.write("set prompt = '\\\n")
  1459. f.write("Mapset <%s> in Location <%s> \\\n" % (mapset, location_name))
  1460. f.write("GRASS GIS %s > '\n" % grass_version)
  1461. f.write("set BOGUS=``;unset BOGUS\n")
  1462. # csh shell rc file left for backward compatibility
  1463. path = os.path.join(userhome, ".grass.cshrc")
  1464. if os.access(path, os.R_OK):
  1465. f.write(readfile(path) + '\n')
  1466. if os.access(grass_env_file, os.R_OK):
  1467. f.write(readfile(grass_env_file) + '\n')
  1468. mail_re = re.compile(r"^ *set *mail *= *")
  1469. for filename in [".cshrc", ".tcshrc", ".login"]:
  1470. path = os.path.join(userhome, filename)
  1471. if os.access(path, os.R_OK):
  1472. s = readfile(path)
  1473. lines = s.splitlines()
  1474. for l in lines:
  1475. if mail_re.match(l):
  1476. f.write(l)
  1477. path = os.getenv('PATH').split(':')
  1478. f.write("set path = ( %s ) \n" % ' '.join(path))
  1479. f.close()
  1480. writefile(tcshrc, readfile(cshrc))
  1481. process = Popen([gpath("etc", "run"), os.getenv('SHELL')])
  1482. os.environ['HOME'] = userhome
  1483. return process
  1484. def bash_startup(location, location_name, grass_env_file):
  1485. # save command history in mapset dir and remember more
  1486. os.environ['HISTFILE'] = os.path.join(location, ".bash_history")
  1487. if not os.getenv('HISTSIZE') and not os.getenv('HISTFILESIZE'):
  1488. os.environ['HISTSIZE'] = "3000"
  1489. # instead of changing $HOME, start bash with:
  1490. # --rcfile "$LOCATION/.bashrc" ?
  1491. # if so, must care be taken to explicitly call .grass.bashrc et al
  1492. # for non-interactive bash batch jobs?
  1493. userhome = os.getenv('HOME') # save original home
  1494. home = location # save .bashrc in $LOCATION
  1495. os.environ['HOME'] = home
  1496. bashrc = os.path.join(home, ".bashrc")
  1497. try_remove(bashrc)
  1498. f = open(bashrc, 'w')
  1499. f.write("test -r ~/.alias && . ~/.alias\n")
  1500. if os.getenv('ISISROOT'):
  1501. # GRASS GIS and ISIS blend
  1502. grass_name = "ISIS-GRASS"
  1503. else:
  1504. grass_name = "GRASS"
  1505. f.write("PS1='{name} {version} ({location}):\\w > '\n".format(
  1506. name=grass_name, version=grass_version, location=location_name))
  1507. # TODO: have a function and/or module to test this
  1508. mask2d_test = 'test -f "$MAPSET_PATH/cell/MASK"'
  1509. mask3d_test = 'test -d "$MAPSET_PATH/grid3/RASTER3D_MASK"'
  1510. # double curly brackets means single one for format function
  1511. # setting LOCATION for backwards compatibility
  1512. f.write(
  1513. """grass_prompt() {{
  1514. MAPSET_PATH="`g.gisenv get=GISDBASE,LOCATION_NAME,MAPSET separator='/'`"
  1515. LOCATION="$MAPSET_PATH"
  1516. if {mask2d_test} && {mask3d_test} ; then
  1517. echo [{both_masks}]
  1518. elif {mask2d_test} ; then
  1519. echo [{mask2d}]
  1520. elif {mask3d_test} ; then
  1521. echo [{mask3d}]
  1522. fi
  1523. }}
  1524. PROMPT_COMMAND=grass_prompt\n""".format(
  1525. both_masks=_("2D and 3D raster MASKs present"),
  1526. mask2d=_("Raster MASK present"),
  1527. mask3d=_("3D raster MASK present"),
  1528. mask2d_test=mask2d_test, mask3d_test=mask3d_test
  1529. ))
  1530. # read other settings (aliases, ...) since environmental variables
  1531. # have been already set by load_env(), see #3462
  1532. for env_file in [os.path.join(userhome, ".grass.bashrc"),
  1533. grass_env_file]:
  1534. if not os.access(env_file, os.R_OK):
  1535. continue
  1536. for line in readfile(env_file).splitlines():
  1537. # Bug related to OS X "SIP", see
  1538. # https://trac.osgeo.org/grass/ticket/3462#comment:13
  1539. if macosx or not line.startswith('export'):
  1540. f.write(line + '\n')
  1541. f.write("export PATH=\"%s\"\n" % os.getenv('PATH'))
  1542. f.write("export HOME=\"%s\"\n" % userhome) # restore user home path
  1543. f.close()
  1544. process = Popen([gpath("etc", "run"), os.getenv('SHELL')])
  1545. os.environ['HOME'] = userhome
  1546. return process
  1547. def default_startup(location, location_name):
  1548. if windows:
  1549. os.environ['PS1'] = "GRASS %s> " % (grass_version)
  1550. # "$ETC/run" doesn't work at all???
  1551. process = subprocess.Popen([os.getenv('SHELL')])
  1552. else:
  1553. os.environ['PS1'] = "GRASS %s (%s):\\w > " % (grass_version, location_name)
  1554. process = Popen([gpath("etc", "run"), os.getenv('SHELL')])
  1555. return process
  1556. def done_message():
  1557. # here was something for batch job but it was never called
  1558. message(_("Done."))
  1559. message("")
  1560. message(_("Goodbye from GRASS GIS"))
  1561. message("")
  1562. def clean_temp():
  1563. message(_("Cleaning up temporary files..."))
  1564. nul = open(os.devnull, 'w')
  1565. call([gpath("etc", "clean_temp")], stdout=nul)
  1566. nul.close()
  1567. def clean_all():
  1568. from grass.script import setup as gsetup
  1569. # clean default sqlite db
  1570. gsetup.clean_default_db()
  1571. # remove leftover temp files
  1572. clean_temp()
  1573. # save 'last used' GISRC after removing variables which shouldn't
  1574. # be saved, e.g. d.mon related
  1575. clean_env(os.environ['GISRC'])
  1576. def grep(pattern, lines):
  1577. """Search lines (list of strings) and return them when beginning matches.
  1578. >>> grep("a", ['abc', 'cab', 'sdr', 'aaa', 'sss'])
  1579. ['abc', 'aaa']
  1580. """
  1581. expr = re.compile(pattern)
  1582. return [elem for elem in lines if expr.match(elem)]
  1583. def print_params():
  1584. """Write compile flags and other configuration to stderr"""
  1585. plat = gpath('include', 'Make', 'Platform.make')
  1586. if not os.path.exists(plat):
  1587. fatal(_("Please install the GRASS GIS development package"))
  1588. fileplat = open(plat)
  1589. linesplat = fileplat.readlines()
  1590. fileplat.close()
  1591. params = sys.argv[2:]
  1592. if not params:
  1593. params = ['arch', 'build', 'compiler', 'path', 'revision', 'version']
  1594. for arg in params:
  1595. if arg == 'path':
  1596. sys.stdout.write("%s\n" % gisbase)
  1597. elif arg == 'arch':
  1598. val = grep('ARCH', linesplat)
  1599. sys.stdout.write("%s\n" % val[0].split('=')[1].strip())
  1600. elif arg == 'build':
  1601. build = gpath('include', 'grass', 'confparms.h')
  1602. filebuild = open(build)
  1603. val = filebuild.readline()
  1604. filebuild.close()
  1605. sys.stdout.write("%s\n" % val.strip().strip('"').strip())
  1606. elif arg == 'compiler':
  1607. val = grep('CC', linesplat)
  1608. sys.stdout.write("%s\n" % val[0].split('=')[1].strip())
  1609. elif arg == 'revision':
  1610. rev = gpath('include', 'grass', 'gis.h')
  1611. filerev = open(rev)
  1612. linesrev = filerev.readlines()
  1613. val = grep('#define GIS_H_VERSION', linesrev)
  1614. filerev.close()
  1615. sys.stdout.write(
  1616. "%s\n" % val[0].split(':')[1].rstrip('$"\n').strip())
  1617. elif arg == 'svn_revision':
  1618. filerev = open(gpath('etc', 'VERSIONNUMBER'))
  1619. linerev = filerev.readline().rstrip('\n')
  1620. filerev.close()
  1621. try:
  1622. revision = linerev.split(' ')[1]
  1623. sys.stdout.write("%s\n" % revision[1:])
  1624. except:
  1625. sys.stdout.write("No SVN revision defined\n")
  1626. elif arg == 'version':
  1627. sys.stdout.write("%s\n" % grass_version)
  1628. else:
  1629. message(_("Parameter <%s> not supported") % arg)
  1630. def get_username():
  1631. """Get name of the current user"""
  1632. if windows:
  1633. user = os.getenv('USERNAME')
  1634. if not user:
  1635. user = "user_name"
  1636. else:
  1637. user = os.getenv('USER')
  1638. if not user:
  1639. user = os.getenv('LOGNAME')
  1640. if not user:
  1641. try:
  1642. p = Popen(['whoami'], stdout=subprocess.PIPE)
  1643. s = p.stdout.read()
  1644. p.wait()
  1645. user = s.strip()
  1646. if type(user) is bytes:
  1647. user = decode(user)
  1648. except:
  1649. pass
  1650. if not user:
  1651. user = "user_%d" % os.getuid()
  1652. return user
  1653. class Parameters(object):
  1654. """Structure to hold standard part of command line parameters"""
  1655. # we don't need to define any methods
  1656. # pylint: disable=R0903
  1657. def __init__(self):
  1658. self.grass_gui = None
  1659. self.create_new = None
  1660. self.exit_grass = None
  1661. self.force_gislock_removal = None
  1662. self.mapset = None
  1663. self.geofile = None
  1664. self.tmp_location = False
  1665. def parse_cmdline(argv, default_gui):
  1666. """Parse the standard part of command line parameters"""
  1667. params = Parameters()
  1668. args = []
  1669. for i in argv:
  1670. # Check if the user asked for the version
  1671. if i in ["-v", "--version"]:
  1672. message("GRASS GIS %s" % grass_version)
  1673. message('\n' + readfile(gpath("etc", "license")))
  1674. sys.exit()
  1675. # Check if the user asked for help
  1676. elif i in ["help", "-h", "-help", "--help", "--h"]:
  1677. help_message(default_gui=default_gui)
  1678. sys.exit()
  1679. # Check if the --text flag was given
  1680. elif i in ["-text", "--text"]:
  1681. params.grass_gui = 'text'
  1682. # Check if the --gtext flag was given
  1683. elif i in ["-gtext", "--gtext"]:
  1684. params.grass_gui = 'gtext'
  1685. # Check if the --gui flag was given
  1686. elif i in ["-gui", "--gui"]:
  1687. params.grass_gui = default_gui
  1688. # Check if the -wxpython flag was given
  1689. elif i in ["-wxpython", "-wx", "--wxpython", "--wx"]:
  1690. params.grass_gui = 'wxpython'
  1691. # Check if the user wants to create a new mapset
  1692. elif i == "-c":
  1693. params.create_new = True
  1694. elif i == "-e":
  1695. params.exit_grass = True
  1696. elif i == "-f":
  1697. params.force_gislock_removal = True
  1698. elif i == "--config":
  1699. print_params()
  1700. sys.exit()
  1701. elif i == "--tmp-location":
  1702. params.tmp_location = True
  1703. else:
  1704. args.append(i)
  1705. if len(args) > 1:
  1706. params.mapset = args[1]
  1707. params.geofile = args[0]
  1708. elif len(args) == 1:
  1709. if params.tmp_location:
  1710. params.geofile = args[0]
  1711. else:
  1712. params.mapset = args[0]
  1713. else:
  1714. params.mapset = None
  1715. return params
  1716. # The main script starts here
  1717. # Get the system name
  1718. windows = sys.platform == 'win32'
  1719. cygwin = "cygwin" in sys.platform
  1720. macosx = "darwin" in sys.platform
  1721. # TODO: it is OK to remove this?
  1722. # at the beginning of this file were are happily getting GISBASE
  1723. # from the environment and we don't care about inconsistencies it might cause
  1724. # The following was commented out because of breaking winGRASS
  1725. # if 'GISBASE' in os.environ:
  1726. # sys.exit(_("ERROR: GRASS GIS is already running "
  1727. # "(environmental variable GISBASE found)"))
  1728. # this is not really an issue, we should be able to overpower another session
  1729. # Set GISBASE
  1730. os.environ['GISBASE'] = gisbase
  1731. def main():
  1732. """The main function which does the whole setup and run procedure
  1733. Only few things are set on the module level.
  1734. """
  1735. # Set default GUI
  1736. default_gui = "wxpython"
  1737. # explain what is happening in debug mode (visible only in debug mode)
  1738. debug("GRASS_DEBUG environmental variable is set. It is meant to be"
  1739. " an internal variable for debugging only this script.\n"
  1740. " Use 'g.gisenv set=\"DEBUG=[0-5]\"'"
  1741. " to turn GRASS GIS debug mode on if you wish to do so.")
  1742. # Set GRASS version number for R interface etc
  1743. # (must be an env var for MS Windows)
  1744. os.environ['GRASS_VERSION'] = grass_version
  1745. # Set the GIS_LOCK variable to current process id
  1746. gis_lock = str(os.getpid())
  1747. os.environ['GIS_LOCK'] = gis_lock
  1748. grass_config_dir = get_grass_config_dir()
  1749. batch_job = get_batch_job_from_env_variable()
  1750. # Parse the command-line options and set several global variables
  1751. batch_exec_param = '--exec'
  1752. try:
  1753. # raises ValueError when not found
  1754. index = sys.argv.index(batch_exec_param)
  1755. batch_job = sys.argv[index + 1:]
  1756. clean_argv = sys.argv[1:index]
  1757. params = parse_cmdline(clean_argv, default_gui=default_gui)
  1758. except ValueError:
  1759. params = parse_cmdline(sys.argv[1:], default_gui=default_gui)
  1760. if params.exit_grass and not params.create_new:
  1761. fatal(_("Flag -e requires also flag -c"))
  1762. if params.tmp_location and not params.geofile:
  1763. fatal(_("Coordinate reference system argument (e.g. EPSG)"
  1764. " is needed for --tmp-location"))
  1765. if params.tmp_location and params.mapset:
  1766. fatal(_("Only one argument (e.g. EPSG) is needed for"
  1767. " --tmp-location, mapset name <{}> provided").format(
  1768. params.mapset))
  1769. # For now, we allow, but not advertise/document, --tmp-location
  1770. # without --exec (usefulness to be evaluated).
  1771. grass_gui = params.grass_gui # put it to variable, it is used a lot
  1772. # TODO: with --tmp-location there is no point in loading settings
  1773. # i.e. rc file from home dir, but the code is too spread out
  1774. # to disable it at this point
  1775. gisrcrc = get_gisrc_from_config_dir(grass_config_dir, batch_job)
  1776. # Set the username
  1777. user = get_username()
  1778. # TODO: this might need to be moved before processing of parameters
  1779. # and getting batch job
  1780. # Set language
  1781. # This has to be called before any _() function call!
  1782. # Subsequent functions are using _() calls and
  1783. # thus must be called only after Language has been set.
  1784. set_language(grass_config_dir)
  1785. # Set shell (needs to be called before load_env())
  1786. sh, shellname = get_shell()
  1787. grass_env_file = get_grass_env_file(sh, grass_config_dir)
  1788. # Load environmental variables from the file (needs to be called
  1789. # before create_tmp())
  1790. load_env(grass_env_file)
  1791. # Create the temporary directory and session grassrc file
  1792. tmpdir = create_tmp(user, gis_lock)
  1793. cleaner = Cleaner()
  1794. cleaner.tmpdir = tmpdir
  1795. # object is not destroyed when its method is registered
  1796. atexit.register(cleaner.cleanup)
  1797. # Create the session grassrc file
  1798. gisrc = create_gisrc(tmpdir, gisrcrc)
  1799. ensure_home()
  1800. # Set PATH, PYTHONPATH, ...
  1801. set_paths(grass_config_dir=grass_config_dir)
  1802. # Set GRASS_PAGER, GRASS_PYTHON, GRASS_GNUPLOT, GRASS_PROJSHARE
  1803. set_defaults()
  1804. set_display_defaults()
  1805. # Set GRASS_HTML_BROWSER
  1806. set_browser()
  1807. # First time user - GISRC is defined in the GRASS script
  1808. if not os.access(gisrc, os.F_OK):
  1809. if grass_gui == 'text' and not params.mapset:
  1810. fatal(_("Unable to start GRASS GIS. You have the choice to:\n"
  1811. " - Launch the graphical user interface with"
  1812. " the '--gui' switch\n"
  1813. " {cmd_name} --gui\n"
  1814. " - Launch with path to "
  1815. "the location/mapset as an argument\n"
  1816. " {cmd_name} /path/to/location/mapset`\n"
  1817. " - Create a location with '-c' and launch in its"
  1818. " PERMANENT mapset\n"
  1819. " {cmd_name} -c EPSG:number /path/to/location\n"
  1820. " {cmd_name} -c geofile /path/to/location\n"
  1821. " - Create manually the GISRC file ({gisrcrc})\n"
  1822. " - Use '--help' for further options\n"
  1823. " {cmd_name} --help\n"
  1824. "See also: https://grass.osgeo.org/{cmd_name}/manuals/helptext.html").format(
  1825. cmd_name=cmd_name, gisrcrc=gisrcrc))
  1826. create_initial_gisrc(gisrc)
  1827. message(_("Starting GRASS GIS..."))
  1828. # Ensure GUI is set
  1829. if batch_job or params.exit_grass:
  1830. grass_gui = 'text'
  1831. else:
  1832. if not grass_gui:
  1833. # if GUI was not set previously (e.g. command line),
  1834. # get it from rc file or env variable
  1835. grass_gui = read_gui(gisrc, default_gui)
  1836. # check that the GUI works but only if not doing a batch job
  1837. grass_gui = check_gui(expected_gui=grass_gui)
  1838. # save GUI only if we are not doibg batch job
  1839. save_gui(gisrc, grass_gui)
  1840. # Parsing argument to get LOCATION
  1841. if not params.mapset and not params.tmp_location:
  1842. # Try interactive startup
  1843. # User selects LOCATION and MAPSET if not set
  1844. if not set_mapset_interactive(grass_gui):
  1845. # No GUI available, update gisrc file
  1846. fatal(_("<{0}> requested, but not available. Run GRASS in text "
  1847. "mode (--text) or install missing package (usually "
  1848. "'grass-gui').").format(grass_gui))
  1849. else:
  1850. # Try non-interactive start up
  1851. if params.tmp_location:
  1852. # tmp loc requires other things to be set as well
  1853. set_mapset(gisrc=gisrc, geofile=params.geofile,
  1854. create_new=True,
  1855. tmp_location=params.tmp_location, tmpdir=tmpdir)
  1856. elif params.create_new and params.geofile:
  1857. set_mapset(gisrc=gisrc, arg=params.mapset,
  1858. geofile=params.geofile, create_new=True)
  1859. else:
  1860. set_mapset(gisrc=gisrc, arg=params.mapset,
  1861. create_new=params.create_new)
  1862. # Set GISDBASE, LOCATION_NAME, MAPSET, LOCATION from $GISRC
  1863. # e.g. wxGUI startup screen writes to the gisrc file,
  1864. # so loading it is the only universal way to obtain the values
  1865. # this suppose that both programs share the right path to gisrc file
  1866. # TODO: perhaps gisrcrc should be removed from here
  1867. # alternatively, we can check validity here with all the info we have
  1868. # about what was used to create gisrc
  1869. mapset_settings = load_gisrc(gisrc, gisrcrc=gisrcrc)
  1870. location = mapset_settings.full_mapset
  1871. # check and create .gislock file
  1872. lock_mapset(mapset_settings.full_mapset, user=user,
  1873. force_gislock_removal=params.force_gislock_removal,
  1874. grass_gui=grass_gui)
  1875. # unlock the mapset which is current at the time of turning off
  1876. # in case mapset was changed
  1877. atexit.register(lambda: unlock_gisrc_mapset(gisrc, gisrcrc))
  1878. # We now own the mapset (set and lock), so we can clean temporary
  1879. # files which previous session may have left behind. We do it even
  1880. # for first time user because the cost is low and first time user
  1881. # doesn't necessarily mean that the mapset is used for the first time.
  1882. clean_temp()
  1883. # build user fontcap if specified but not present
  1884. make_fontcap()
  1885. # TODO: is this really needed? Modules should call this when/if required.
  1886. ensure_db_connected(location)
  1887. # Display the version and license info
  1888. # only non-error, interactive version continues from here
  1889. if batch_job:
  1890. returncode = run_batch_job(batch_job)
  1891. clean_all()
  1892. sys.exit(returncode)
  1893. elif params.exit_grass:
  1894. # clean always at exit, cleans whatever is current mapset based on
  1895. # the GISRC env variable
  1896. clean_all()
  1897. sys.exit(0)
  1898. else:
  1899. clear_screen()
  1900. show_banner()
  1901. say_hello()
  1902. show_info(shellname=shellname,
  1903. grass_gui=grass_gui, default_gui=default_gui)
  1904. if grass_gui == "wxpython":
  1905. message(_("Launching <%s> GUI in the background, please wait...")
  1906. % grass_gui)
  1907. if sh in ['csh', 'tcsh']:
  1908. shell_process = csh_startup(mapset_settings.full_mapset,
  1909. mapset_settings.location,
  1910. mapset_settings.mapset,
  1911. grass_env_file)
  1912. elif sh in ['bash', 'msh', 'cygwin']:
  1913. shell_process = bash_startup(mapset_settings.full_mapset,
  1914. mapset_settings.location,
  1915. grass_env_file)
  1916. else:
  1917. shell_process = default_startup(mapset_settings.full_mapset,
  1918. mapset_settings.location)
  1919. # start GUI and register shell PID in rc file
  1920. start_gui(grass_gui)
  1921. kv = read_gisrc(gisrc)
  1922. kv['PID'] = str(shell_process.pid)
  1923. write_gisrc(kv, gisrc)
  1924. exit_val = shell_process.wait()
  1925. if exit_val != 0:
  1926. warning(_("Failed to start shell '%s'") % os.getenv('SHELL'))
  1927. # close GUI if running
  1928. close_gui()
  1929. # here we are at the end of grass session
  1930. clear_screen()
  1931. clean_all()
  1932. if not params.tmp_location:
  1933. writefile(gisrcrc, readfile(gisrc))
  1934. # After this point no more grass modules may be called
  1935. # done message at last: no atexit.register()
  1936. # or register done_message()
  1937. done_message()
  1938. if __name__ == '__main__':
  1939. main()