grass.py 74 KB

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