grass.py 74 KB

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