grass.py 77 KB

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