grass.py 76 KB

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