grass.py 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665
  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. # PURPOSE: Sets up environment variables, parses any remaining
  17. # command line options for setting the GISDBASE, LOCATION,
  18. # and/or MAPSET. Finally it starts GRASS with the appropriate
  19. # user interface and cleans up after it is finished.
  20. # COPYRIGHT: (C) 2000-2015 by the GRASS Development Team
  21. #
  22. # This program is free software under the GNU General
  23. # Public License (>=v2). Read the file COPYING that
  24. # comes with GRASS for details.
  25. #
  26. #############################################################################
  27. import sys
  28. import os
  29. import atexit
  30. import string
  31. import subprocess
  32. import re
  33. import platform
  34. import tempfile
  35. # Variables substituted during build process
  36. if 'GISBASE' in os.environ:
  37. gisbase = os.environ['GISBASE']
  38. else:
  39. gisbase = "@GISBASE@"
  40. cmd_name = "@START_UP@"
  41. grass_version = "@GRASS_VERSION_NUMBER@"
  42. ld_library_path_var = '@LD_LIBRARY_PATH_VAR@'
  43. if 'GRASS_PROJSHARE' in os.environ:
  44. config_projshare = os.environ['GRASS_PROJSHARE']
  45. else:
  46. config_projshare = "@CONFIG_PROJSHARE@"
  47. # configuration directory
  48. grass_env_file = None # see check_shell()
  49. if sys.platform == 'win32':
  50. grass_config_dirname = "GRASS7"
  51. grass_config_dir = os.path.join(os.getenv('APPDATA'), grass_config_dirname)
  52. else:
  53. grass_config_dirname = ".grass7"
  54. grass_config_dir = os.path.join(os.getenv('HOME'), grass_config_dirname)
  55. gisbase = os.path.normpath(gisbase)
  56. # i18N
  57. import gettext
  58. gettext.install('grasslibs', os.path.join(gisbase, 'locale'))
  59. tmpdir = None
  60. lockfile = None
  61. remove_lockfile = True
  62. location = None
  63. grass_gui = None
  64. def warning(text):
  65. sys.stderr.write(_("WARNING") + ': ' + text + os.linesep)
  66. def try_remove(path):
  67. try:
  68. os.remove(path)
  69. except:
  70. pass
  71. def try_rmdir(path):
  72. try:
  73. os.rmdir(path)
  74. except:
  75. pass
  76. def clean_env(gisrc):
  77. env_curr = read_gisrc(gisrc)
  78. env_new = {}
  79. for k,v in env_curr.iteritems():
  80. if 'MONITOR' not in k:
  81. env_new[k] = v
  82. write_gisrc(env_new, gisrc)
  83. def cleanup_dir(path):
  84. if not path:
  85. return
  86. for root, dirs, files in os.walk(path, topdown=False):
  87. for name in files:
  88. try_remove(os.path.join(root, name))
  89. for name in dirs:
  90. try_rmdir(os.path.join(root, name))
  91. def cleanup(tmpdir):
  92. global lockfile, remove_lockfile
  93. # all exits after setting up tmp dirs (system/location) should
  94. # also tidy it up
  95. cleanup_dir(tmpdir)
  96. try_rmdir(tmpdir)
  97. if location:
  98. tmpdir_loc = os.path.join(location, ".tmp")
  99. cleanup_dir(tmpdir_loc)
  100. try_rmdir(tmpdir_loc)
  101. # remove lock-file if requested
  102. if lockfile and remove_lockfile:
  103. try_remove(lockfile)
  104. def fatal(msg):
  105. sys.stderr.write("%s: " % _('ERROR') + msg + os.linesep)
  106. sys.exit(_("Exiting..."))
  107. def message(msg):
  108. sys.stderr.write(msg + "\n")
  109. sys.stderr.flush()
  110. # mechanism meant for debugging this script (only)
  111. # private global to store if we are debugging
  112. _DEBUG = None
  113. def is_debug():
  114. """Returns True if we are in debug mode
  115. For debug messages use ``debug()``.
  116. """
  117. global _DEBUG
  118. if _DEBUG is not None:
  119. return _DEBUG
  120. _DEBUG = os.getenv('GRASS_DEBUG')
  121. # translate to bool (no or empty variable means false)
  122. if _DEBUG:
  123. _DEBUG = True
  124. else:
  125. _DEBUG = False
  126. return _DEBUG
  127. def debug(msg):
  128. """Print a debug message if in debug mode
  129. Do not use translatable strings for debug messages.
  130. """
  131. if is_debug():
  132. sys.stderr.write("DEBUG: %s\n" % msg)
  133. sys.stderr.flush()
  134. def readfile(path):
  135. f = open(path, 'r')
  136. s = f.read()
  137. f.close()
  138. return s
  139. def writefile(path, s):
  140. f = open(path, 'w')
  141. f.write(s)
  142. f.close()
  143. def call(cmd, **kwargs):
  144. if windows:
  145. kwargs['shell'] = True
  146. return subprocess.call(cmd, **kwargs)
  147. def Popen(cmd, **kwargs):
  148. if windows:
  149. kwargs['shell'] = True
  150. return subprocess.Popen(cmd, **kwargs)
  151. def gpath(*args):
  152. """Costruct path to file or directory in GRASS GIS installation
  153. Can be called only after gisbase was set.
  154. """
  155. return os.path.join(gisbase, *args)
  156. # for wxpath
  157. _WXPYTHON_BASE = None
  158. def wxpath(*args):
  159. """Costruct path to file or directory in GRASS wxGUI
  160. Can be called only after gisbase was set.
  161. This function does not check if the directories exist or if GUI works
  162. this must be done by the caller if needed.
  163. """
  164. global _WXPYTHON_BASE
  165. if not _WXPYTHON_BASE:
  166. # this can be called only after gisbase was set
  167. _WXPYTHON_BASE = gpath("gui", "wxpython")
  168. return os.path.join(_WXPYTHON_BASE, *args)
  169. # using format for most but leaving usage of template for the dynamic ones
  170. # two different methods are easy way to implement two phase construction
  171. help_text = r"""GRASS GIS $VERSION_NUMBER
  172. Geographic Resources Analysis Support System (GRASS GIS).
  173. {usage}:
  174. $CMD_NAME [-h | -help | --help | --h] [-v | --version]
  175. [-c | -c geofile | -c EPSG:code[:datum_trans]]
  176. [-e] [-f] [-text | -gtext | -gui] [--config param]
  177. [[[GISDBASE/]LOCATION_NAME/]MAPSET]
  178. $CMD_NAME [FLAG]... GISDBASE/LOCATION_NAME/MAPSET exec MODULE [PARAM]...
  179. {flags}:
  180. -h or -help or --help or --h {help_flag}
  181. -v or --version {version_flag}
  182. -c {create}
  183. -e {exit_after}
  184. -f {force_removal}
  185. -text {text}
  186. {text_detail}
  187. -gtext {gtext}
  188. {gtext_detail}
  189. -gui {gui}
  190. {gui_detail}
  191. --config {config}
  192. {config_detail}
  193. exec MODULE {exec_}
  194. {exec_detail}
  195. {params}:
  196. GISDBASE {gisdbase}
  197. {gisdbase_detail}
  198. LOCATION_NAME {location}
  199. {location_detail}
  200. MAPSET {mapset}
  201. GISDBASE/LOCATION_NAME/MAPSET {full_mapset}
  202. {env_vars}:
  203. GRASS_GUI {gui_var}
  204. GRASS_HTML_BROWSER {html_var}
  205. GRASS_ADDON_PATH {addon_path_var}
  206. GRASS_ADDON_BASE {addon_base_var}
  207. GRASS_BATCH_JOB {batch_var}
  208. GRASS_PYTHON {python_var}
  209. """.format(
  210. usage=_("Usage"),
  211. flags=_("Flags"),
  212. help_flag=_("print this help message"),
  213. version_flag=_("show version information and exit"),
  214. create=_("create given database, location or mapset if it doesn't exist"),
  215. exit_after=_("exit after creation of location or mapset. Only with -c flag"),
  216. force_removal=_("force removal of .gislock if exists (use with care!). Only with -text flag"),
  217. text=_("use text based interface (skip welcome screen)"),
  218. text_detail=_("and set as default"),
  219. gtext=_("use text based interface (show welcome screen)"),
  220. gtext_detail=_("and set as default"),
  221. gui=_("use $DEFAULT_GUI graphical user interface"),
  222. gui_detail=_("and set as default"),
  223. config=_("print GRASS configuration parameters"),
  224. config_detail=_("options: arch,build,compiler,path,revision"),
  225. params=_("Parameters"),
  226. gisdbase=_("initial GRASS GIS database directory"),
  227. gisdbase_detail=_("directory containing Locations"),
  228. location=_("initial GRASS Location"),
  229. location_detail=_("directory containing Mapsets with one common coordinate system (projection)"),
  230. mapset=_("initial GRASS Mapset"),
  231. full_mapset=_("fully qualified initial Mapset directory"),
  232. env_vars=_("Environment variables relevant for startup"),
  233. gui_var=_("select GUI (text, gui, gtext)"),
  234. html_var=_("set html web browser for help pages"),
  235. addon_path_var=_("set additional path(s) to local GRASS modules or user scripts"),
  236. addon_base_var=_("set additional GISBASE for locally installed GRASS Addons"),
  237. batch_var=_("shell script to be processed as batch job"),
  238. python_var=_("set python shell name to override 'python'"),
  239. exec_=_("execute GRASS module or script"),
  240. exec_detail=_("any executable will be executed in GRASS session"),
  241. )
  242. def help_message():
  243. t = string.Template(help_text)
  244. s = t.substitute(CMD_NAME=cmd_name, DEFAULT_GUI=default_gui,
  245. VERSION_NUMBER=grass_version)
  246. sys.stderr.write(s)
  247. def create_tmp(user, gis_lock):
  248. """Create temporary directory
  249. :param user: user name to be used in the directory name
  250. :param gis_lock: session lock filename to be used in the directory name
  251. """
  252. # use $TMPDIR if it exists, then $TEMP, otherwise /tmp
  253. tmp = os.getenv('TMPDIR')
  254. if not tmp:
  255. tmp = os.getenv('TEMP')
  256. if not tmp:
  257. tmp = os.getenv('TMP')
  258. if not tmp:
  259. tmp = tempfile.gettempdir()
  260. if tmp:
  261. tmpdir = os.path.join(tmp, "grass7-%(user)s-%(lock)s" % {'user': user,
  262. 'lock': gis_lock})
  263. try:
  264. os.mkdir(tmpdir, 0700)
  265. except:
  266. tmp = None
  267. if not tmp:
  268. for ttmp in ("/tmp", "/var/tmp", "/usr/tmp"):
  269. tmp = ttmp
  270. tmpdir = os.path.join(tmp, "grass7-%(user)s-%(lock)s" % {
  271. 'user': user, 'lock': gis_lock})
  272. try:
  273. os.mkdir(tmpdir, 0700)
  274. except:
  275. tmp = None
  276. if tmp:
  277. break
  278. if not tmp:
  279. fatal(_("Unable to create temporary directory <grass7-%(user)s-"
  280. "%(lock)s>! Exiting.") % {'user': user, 'lock': gis_lock})
  281. # promoting the variable even if it was not defined before
  282. os.environ['TMPDIR'] = tmpdir
  283. return tmpdir
  284. def create_gisrc(tmpdir, gisrcrc):
  285. # Set the session grassrc file
  286. gisrc = os.path.join(tmpdir, "gisrc")
  287. os.environ['GISRC'] = gisrc
  288. # remove invalid GISRC file to avoid disturbing error messages:
  289. try:
  290. s = readfile(gisrcrc)
  291. if "UNKNOWN" in s:
  292. try_remove(gisrcrc)
  293. s = None
  294. except:
  295. s = None
  296. # Copy the global grassrc file to the session grassrc file
  297. if s:
  298. writefile(gisrc, s)
  299. return gisrc
  300. def read_gisrc(filename):
  301. kv = {}
  302. try:
  303. f = open(filename, 'r')
  304. except IOError:
  305. return kv
  306. for line in f:
  307. try:
  308. k, v = line.split(':', 1)
  309. except ValueError as e:
  310. warning(_("Invalid line in RC file ({file}):"
  311. " '{line}' ({error})\n").format(
  312. line=line, error=e, file=filename))
  313. continue
  314. kv[k.strip()] = v.strip()
  315. f.close()
  316. return kv
  317. def read_env_file(path):
  318. kv = {}
  319. f = open(path, 'r')
  320. for line in f:
  321. k, v = line.split(':', 1)
  322. kv[k.strip()] = v.strip()
  323. f.close()
  324. return kv
  325. def write_gisrc(kv, filename):
  326. f = open(filename, 'w')
  327. for k, v in kv.iteritems():
  328. f.write("%s: %s\n" % (k, v))
  329. f.close()
  330. def read_gui(default_gui):
  331. grass_gui = None
  332. # At this point the GRASS user interface variable has been set from the
  333. # command line, been set from an external environment variable, or is
  334. # not set. So we check if it is not set
  335. # Check for a reference to the GRASS user interface in the grassrc file
  336. if os.access(gisrc, os.R_OK):
  337. kv = read_gisrc(gisrc)
  338. if 'GRASS_GUI' in os.environ:
  339. grass_gui = os.environ['GRASS_GUI']
  340. elif 'GUI' in kv:
  341. grass_gui = kv['GUI']
  342. elif 'GRASS_GUI' in kv:
  343. # For backward compatibility (GRASS_GUI renamed to GUI)
  344. grass_gui = kv['GRASS_GUI']
  345. else:
  346. # Set the GRASS user interface to the default if needed
  347. grass_gui = default_gui
  348. if not grass_gui:
  349. grass_gui = default_gui
  350. if grass_gui == 'gui':
  351. grass_gui = default_gui
  352. # FIXME oldtcltk, gis.m, d.m no longer exist (remove this around 7.2)
  353. if grass_gui in ['d.m', 'gis.m', 'oldtcltk', 'tcltk']:
  354. warning(_("GUI <%s> not supported in this version") % grass_gui)
  355. grass_gui = default_gui
  356. return grass_gui
  357. def path_prepend(dir, var):
  358. path = os.getenv(var)
  359. if path:
  360. path = dir + os.pathsep + path
  361. else:
  362. path = dir
  363. os.environ[var] = path
  364. def path_append(dir, var):
  365. path = os.getenv(var)
  366. if path:
  367. path = path + os.pathsep + dir
  368. else:
  369. path = dir
  370. os.environ[var] = path
  371. def set_paths():
  372. # addons (path)
  373. addon_path = os.getenv('GRASS_ADDON_PATH')
  374. if addon_path:
  375. for path in addon_path.split(os.pathsep):
  376. path_prepend(addon_path, 'PATH')
  377. # addons (base)
  378. addon_base = os.getenv('GRASS_ADDON_BASE')
  379. if not addon_base:
  380. addon_base = os.path.join(grass_config_dir, 'addons')
  381. os.environ['GRASS_ADDON_BASE'] = addon_base
  382. if not windows:
  383. path_prepend(os.path.join(addon_base, 'scripts'), 'PATH')
  384. path_prepend(os.path.join(addon_base, 'bin'), 'PATH')
  385. # standard installation
  386. if not windows:
  387. path_prepend(gpath('scripts'), 'PATH')
  388. path_prepend(gpath('bin'), 'PATH')
  389. # Set PYTHONPATH to find GRASS Python modules
  390. if os.path.exists(gpath('gui', 'wxpython')):
  391. path_prepend(gpath('gui', 'wxpython'), 'PYTHONPATH')
  392. if os.path.exists(gpath('etc', 'python')):
  393. path_prepend(gpath('etc', 'python'), 'PYTHONPATH')
  394. # set path for the GRASS man pages
  395. grass_man_path = gpath('docs', 'man')
  396. addons_man_path = os.path.join(addon_base, 'docs', 'man')
  397. man_path = os.getenv('MANPATH')
  398. sys_man_path = None
  399. if man_path:
  400. path_prepend(addons_man_path, 'MANPATH')
  401. path_prepend(grass_man_path, 'MANPATH')
  402. else:
  403. try:
  404. nul = open(os.devnull, 'w')
  405. p = Popen(['manpath'], stdout=subprocess.PIPE, stderr=nul)
  406. nul.close()
  407. s = p.stdout.read()
  408. p.wait()
  409. sys_man_path = s.strip()
  410. except:
  411. pass
  412. if sys_man_path:
  413. os.environ['MANPATH'] = sys_man_path
  414. path_prepend(addons_man_path, 'MANPATH')
  415. path_prepend(grass_man_path, 'MANPATH')
  416. else:
  417. os.environ['MANPATH'] = addons_man_path
  418. path_prepend(grass_man_path, 'MANPATH')
  419. def find_exe(pgm):
  420. for dir in os.getenv('PATH').split(os.pathsep):
  421. path = os.path.join(dir, pgm)
  422. if os.access(path, os.X_OK):
  423. return path
  424. return None
  425. def set_defaults():
  426. # GRASS_PAGER
  427. if not os.getenv('GRASS_PAGER'):
  428. if find_exe("more"):
  429. pager = "more"
  430. elif find_exe("less"):
  431. pager = "less"
  432. elif windows:
  433. pager = "more"
  434. else:
  435. pager = "cat"
  436. os.environ['GRASS_PAGER'] = pager
  437. # GRASS_PYTHON
  438. if not os.getenv('GRASS_PYTHON'):
  439. if windows:
  440. os.environ['GRASS_PYTHON'] = "python.exe"
  441. else:
  442. os.environ['GRASS_PYTHON'] = "python"
  443. # GRASS_GNUPLOT
  444. if not os.getenv('GRASS_GNUPLOT'):
  445. os.environ['GRASS_GNUPLOT'] = "gnuplot -persist"
  446. # GRASS_PROJSHARE
  447. if not os.getenv('GRASS_PROJSHARE'):
  448. os.environ['GRASS_PROJSHARE'] = config_projshare
  449. def set_browser():
  450. # GRASS_HTML_BROWSER
  451. browser = os.getenv('GRASS_HTML_BROWSER')
  452. if not browser:
  453. if macosx:
  454. # OSX doesn't execute browsers from the shell PATH - route thru a
  455. # script
  456. browser = gpath('etc', "html_browser_mac.sh")
  457. os.environ['GRASS_HTML_BROWSER_MACOSX'] = "-b com.apple.helpviewer"
  458. if windows:
  459. browser = "start"
  460. elif cygwin:
  461. browser = "explorer"
  462. else:
  463. # the usual suspects
  464. browsers = ["xdg-open", "x-www-browser", "htmlview", "konqueror", "mozilla",
  465. "mozilla-firefox", "firefox", "iceweasel", "opera",
  466. "netscape", "dillo", "lynx", "links", "w3c"]
  467. for b in browsers:
  468. if find_exe(b):
  469. browser = b
  470. break
  471. elif macosx:
  472. # OSX doesn't execute browsers from the shell PATH - route thru a
  473. # script
  474. os.environ['GRASS_HTML_BROWSER_MACOSX'] = "-b %s" % browser
  475. browser = gpath('etc', "html_browser_mac.sh")
  476. if not browser:
  477. warning(_("Searched for a web browser, but none found"))
  478. # even so we set konqueror to make lib/gis/parser.c happy:
  479. # TODO: perhaps something more probable would be better, e.g. xdg-open
  480. browser = "konqueror"
  481. os.environ['GRASS_HTML_BROWSER'] = browser
  482. def create_initial_gisrc(filename):
  483. # for convenience, define GISDBASE as pwd:
  484. s = r"""GISDBASE: %s
  485. LOCATION_NAME: <UNKNOWN>
  486. MAPSET: <UNKNOWN>
  487. """ % os.getcwd()
  488. writefile(filename, s)
  489. def check_gui(expected_gui):
  490. grass_gui = expected_gui
  491. # Check if we are running X windows by checking the DISPLAY variable
  492. if os.getenv('DISPLAY') or windows or macosx:
  493. # Check if python is working properly
  494. if expected_gui in ('wxpython', 'gtext'):
  495. nul = open(os.devnull, 'w')
  496. p = Popen([os.environ['GRASS_PYTHON']], stdin=subprocess.PIPE,
  497. stdout=nul, stderr=nul)
  498. nul.close()
  499. p.stdin.write("variable=True")
  500. p.stdin.close()
  501. p.wait()
  502. if p.returncode != 0:
  503. # Python was not found - switch to text interface mode
  504. warning(_("The python command does not work as expected!\n"
  505. "Please check your GRASS_PYTHON environment variable.\n"
  506. "Use the -help option for details.\n"
  507. "Switching to text based interface mode.\n\n"
  508. "Hit RETURN to continue.\n"))
  509. sys.stdin.readline()
  510. grass_gui = 'text'
  511. else:
  512. # Display a message if a graphical interface was expected
  513. if expected_gui != 'text':
  514. # Set the interface mode to text
  515. warning(_("It appears that the X Windows system is not active.\n"
  516. "A graphical based user interface is not supported.\n"
  517. "(DISPLAY variable is not set.)\n"
  518. "Switching to text based interface mode.\n\n"
  519. "Hit RETURN to continue.\n"))
  520. sys.stdin.readline()
  521. grass_gui = 'text'
  522. return grass_gui
  523. def save_gui(gisrc, grass_gui):
  524. # Save the user interface variable in the grassrc file - choose a temporary
  525. # file name that should not match another file
  526. if os.access(gisrc, os.F_OK):
  527. kv = read_gisrc(gisrc)
  528. kv['GUI'] = grass_gui
  529. write_gisrc(kv, gisrc)
  530. def create_location(gisdbase, location, geostring):
  531. """Create GRASS Location using georeferenced file or EPSG
  532. EPSG code format is ``EPSG:code`` or ``EPSG:code:datum_trans``.
  533. :param gisdbase: Path to GRASS GIS database directory
  534. :param location: name of new Location
  535. :param geostring: path to a georeferenced file or EPSG code
  536. """
  537. if gpath('etc', 'python') not in sys.path:
  538. sys.path.append(gpath('etc', 'python'))
  539. from grass.script import core as gcore # pylint: disable=E0611
  540. try:
  541. if geostring and geostring.upper().find('EPSG:') > -1:
  542. # create location using EPSG code
  543. epsg = geostring.split(':', 1)[1]
  544. if ':' in epsg:
  545. epsg, datum_trans = epsg.split(':', 1)
  546. else:
  547. datum_trans = None
  548. gcore.create_location(gisdbase, location,
  549. epsg=epsg, datum_trans=datum_trans)
  550. else:
  551. # create location using georeferenced file
  552. gcore.create_location(gisdbase, location,
  553. filename=geostring)
  554. except gcore.ScriptError as e:
  555. fatal(e.value.strip('"').strip("'").replace('\\n', os.linesep))
  556. # interface created according to the current usage
  557. def is_mapset_valid(full_mapset):
  558. """Return True if GRASS Mapset is valid"""
  559. return os.access(os.path.join(full_mapset, "WIND"), os.R_OK)
  560. def is_location_valid(gisdbase, location):
  561. """Return True if GRASS Location is valid
  562. :param gisdbase: Path to GRASS GIS database directory
  563. :param location: name of a Location
  564. """
  565. return os.access(os.path.join(gisdbase, location,
  566. "PERMANENT", "DEFAULT_WIND"), os.F_OK)
  567. # basically checking location, possibly split into two functions
  568. # (mapset one can call location one)
  569. def get_mapset_invalid_reason(gisdbase, location, mapset):
  570. """Returns a message describing what is wrong with the Mapset
  571. :param gisdbase: Path to GRASS GIS database directory
  572. :param location: name of a Location
  573. :param mapset: name of a Mapset
  574. :returns: translated message
  575. """
  576. full_location = os.path.join(gisdbase, location)
  577. if not os.path.exists(full_location):
  578. return _("Location <%s> doesn't exist") % full_location
  579. elif 'PERMANENT' not in os.listdir(full_location):
  580. return _("<%s> is not a valid GRASS Location"
  581. " because PERMANENT Mapset is missing") % full_location
  582. elif not os.path.isdir(os.path.join(full_location, 'PERMANENT')):
  583. return _("<%s> is not a valid GRASS Location"
  584. " because PERMANENT is not a directory") % full_location
  585. elif not os.path.isfile((os.path.join(full_location,
  586. 'PERMANENT', 'DEFAULT_WIND'))):
  587. return _("<%s> is not a valid GRASS Location"
  588. " because PERMANENT Mapset does not have a DEFAULT_WIND file"
  589. " (default computational region)") % full_location
  590. else:
  591. return _("Mapset <{mapset}> doesn't exist in GRASS Location <{loc}>. "
  592. "A new mapset can be created by '-c' switch.").format(
  593. mapset=mapset, loc=location)
  594. def set_mapset(arg, geofile=None, create_new=False):
  595. """Selected Location and Mapset are checked and created if requested
  596. The gisrc (GRASS environment file) is written at the end.
  597. """
  598. global gisdbase, location_name, mapset, location
  599. # Try non-interactive startup
  600. l = None
  601. if arg == '-':
  602. if location:
  603. l = location
  604. else:
  605. l = arg
  606. if l:
  607. if l == '.':
  608. l = os.getcwd()
  609. elif not os.path.isabs(l):
  610. l = os.path.abspath(l)
  611. l, mapset = os.path.split(l)
  612. if not mapset:
  613. l, mapset = os.path.split(l)
  614. l, location_name = os.path.split(l)
  615. gisdbase = l
  616. if gisdbase and location_name and mapset:
  617. location = os.path.join(gisdbase, location_name, mapset)
  618. # check if 'location' is a valid GRASS location/mapset
  619. if not is_mapset_valid(location):
  620. if not create_new:
  621. # 'location' is not valid, check if 'location_name' is
  622. # a valid GRASS location
  623. fatal(get_mapset_invalid_reason(gisdbase, location_name, mapset))
  624. else:
  625. # 'location' is not valid, the user wants to create
  626. # mapset on the fly
  627. if not is_location_valid(gisdbase, location_name):
  628. # 'location_name' is not a valid GRASS location,
  629. # create new location and 'PERMANENT' mapset
  630. gisdbase = os.path.join(gisdbase, location_name)
  631. location_name = mapset
  632. mapset = "PERMANENT"
  633. if is_location_valid(gisdbase, location_name):
  634. fatal(_("Failed to create new location. "
  635. "The location <%s> already exists." % location_name))
  636. create_location(gisdbase, location_name, geofile)
  637. else:
  638. # 'location_name' is a valid GRASS location,
  639. # create new mapset
  640. os.mkdir(location)
  641. # copy PERMANENT/DEFAULT_WIND to <mapset>/WIND
  642. s = readfile(os.path.join(gisdbase, location_name,
  643. "PERMANENT", "DEFAULT_WIND"))
  644. writefile(os.path.join(location, "WIND"), s)
  645. message(_("Missing WIND file fixed"))
  646. if os.access(gisrc, os.R_OK):
  647. kv = read_gisrc(gisrc)
  648. else:
  649. kv = {}
  650. kv['GISDBASE'] = gisdbase
  651. kv['LOCATION_NAME'] = location_name
  652. kv['MAPSET'] = mapset
  653. write_gisrc(kv, gisrc)
  654. else:
  655. fatal(_("GISDBASE, LOCATION_NAME and MAPSET variables not set properly.\n"
  656. "Interactive startup needed."))
  657. def set_mapset_interactive(grass_gui):
  658. """User selects Location and Mapset in an interative way
  659. The gisrc (GRASS environment file) is written at the end.
  660. """
  661. # Check for text interface
  662. if grass_gui == 'text':
  663. pass
  664. # Check for GUI
  665. elif grass_gui in ('gtext', 'wxpython'):
  666. gui_startup(grass_gui)
  667. else:
  668. # Shouldn't need this but you never know
  669. fatal(_("Invalid user interface specified - <%s>. "
  670. "Use the --help option to see valid interface names.") % grass_gui)
  671. def gui_startup(grass_gui):
  672. if grass_gui in ('wxpython', 'gtext'):
  673. ret = call([os.getenv('GRASS_PYTHON'), wxpath("gis_set.py")])
  674. if ret == 0:
  675. pass
  676. elif ret == 1:
  677. # The startup script printed an error message so wait
  678. # for user to read it
  679. message(_("Error in GUI startup. If necessary, please "
  680. "report this error to the GRASS developers.\n"
  681. "Switching to text mode now.\n\n"
  682. "Hit RETURN to continue..."))
  683. sys.stdin.readline()
  684. os.execlp(cmd_name, "-text")
  685. sys.exit(1)
  686. elif ret == 2:
  687. # User wants to exit from GRASS
  688. message(_("Received EXIT message from GUI.\nGRASS is not started. Bye."))
  689. sys.exit(0)
  690. else:
  691. fatal(_("Invalid return code from GUI startup script.\n"
  692. "Please advise GRASS developers of this error."))
  693. def load_gisrc(gisrc):
  694. global gisdbase, location_name, mapset, location
  695. kv = read_gisrc(gisrc)
  696. gisdbase = kv.get('GISDBASE')
  697. location_name = kv.get('LOCATION_NAME')
  698. mapset = kv.get('MAPSET')
  699. if not gisdbase or not location_name or not mapset:
  700. fatal(_("Error reading data path information from g.gisenv.\n"
  701. "GISDBASE=%(gisbase)s\n"
  702. "LOCATION_NAME=%(location)s\n"
  703. "MAPSET=%(mapset)s\n\n"
  704. "Check the <%(file)s> file." % \
  705. {'gisbase': gisdbase, 'location': location_name,
  706. 'mapset': mapset, 'file': gisrcrc}))
  707. location = os.path.join(gisdbase, location_name, mapset)
  708. # load environmental variables from grass_env_file
  709. def load_env():
  710. if not os.access(grass_env_file, os.R_OK):
  711. return
  712. for line in readfile(grass_env_file).split(os.linesep):
  713. try:
  714. k, v = map(lambda x: x.strip(), line.strip().split(' ', 1)[1].split('=', 1))
  715. except:
  716. continue
  717. os.environ[k] = v
  718. # Allow for mixed ISIS-GRASS Environment
  719. if os.getenv('ISISROOT'):
  720. isis = os.getenv('ISISROOT')
  721. os.environ['ISIS_LIB'] = isis + os.sep + "lib"
  722. os.environ['ISIS_3RDPARTY'] = isis + os.sep + "3rdParty" + os.sep + "lib"
  723. os.environ['QT_PLUGIN_PATH'] = isis + os.sep + "3rdParty" + os.sep + "plugins"
  724. #os.environ['ISIS3DATA'] = isis + "$ISIS3DATA"
  725. libpath = os.getenv('LD_LIBRARY_PATH', '')
  726. isislibpath = os.getenv('ISIS_LIB')
  727. isis3rdparty = os.getenv('ISIS_3RDPARTY')
  728. os.environ['LD_LIBRARY_PATH'] = libpath + os.pathsep + isislibpath + os.pathsep + isis3rdparty
  729. def set_language():
  730. # This function is used to override system default language and locale
  731. # Such override can be requested only from wxGUI
  732. # An override if user has provided correct environmental variables as
  733. # LC_MESSAGES or LANG is not necessary.
  734. # Unfortunately currently a working solution for Windows is lacking
  735. # thus it always on Vista and XP will print an error.
  736. # See discussion for Windows not following its own documentation and
  737. # not accepting ISO codes as valid locale identifiers http://bugs.python.org/issue10466
  738. import locale
  739. language = 'None' # Such string sometimes is present in wx file
  740. encoding = None
  741. # Override value is stored in wxGUI preferences file.
  742. # As it's the only thing required, we'll just grep it out.
  743. try:
  744. fd = open(os.path.join(grass_config_dir, 'wx'), 'r')
  745. except:
  746. # Even if there is no override, we still need to set locale.
  747. pass
  748. else:
  749. for line in fd:
  750. if re.search('^language', line):
  751. line = line.rstrip(' %s' % os.linesep)
  752. language = ''.join(line.split(';')[-1:])
  753. break
  754. fd.close()
  755. if language == 'None' or language == '' or not language:
  756. # Language override is disabled (system language specified)
  757. # As by default program runs with C locale, but users expect to
  758. # have their default locale, we'll just set default locale
  759. try:
  760. locale.setlocale(locale.LC_ALL, '')
  761. except locale.Error as e:
  762. # If we get here, system locale settings are terribly wrong
  763. # There is no point to continue as GRASS/Python will fail
  764. # in some other unpredictable way.
  765. print "System locale is not usable. It indicates misconfigured environment."
  766. print "Reported error message: %s" % e
  767. sys.exit("Fix system locale settings and then try again.")
  768. language, encoding = locale.getdefaultlocale()
  769. if not language:
  770. warning(_("Default locale settings are missing. GRASS running with C locale."))
  771. return
  772. else:
  773. debug("A language override has been requested."
  774. " Trying to switch GRASS into '%s'..." % language)
  775. try:
  776. locale.setlocale(locale.LC_ALL, language)
  777. except locale.Error as e:
  778. try:
  779. # Locale lang.encoding might be missing. Let's try
  780. # UTF-8 encoding before giving up as on Linux systems
  781. # lang.UTF-8 locales are more common than legacy
  782. # ISO-8859 ones.
  783. encoding = 'UTF-8'
  784. normalized = locale.normalize('%s.%s' % (language, encoding))
  785. locale.setlocale(locale.LC_ALL, normalized)
  786. except locale.Error as e:
  787. # The last attempt...
  788. try:
  789. encoding = locale.getpreferredencoding()
  790. normalized = locale.normalize('%s.%s' % (language, encoding))
  791. locale.setlocale(locale.LC_ALL, normalized)
  792. except locale.Error as e:
  793. # If we got so far, attempts to set up language and locale have failed
  794. # on this system
  795. sys.stderr.write("Failed to enforce user specified language '%s' with error: '%s'\n" % (language, e))
  796. sys.stderr.write("A LANGUAGE environmental variable has been set.\nPart of messages will be displayed in the requested language.\n")
  797. # Even if setting locale will fail, let's set LANG in a hope,
  798. # that UI will use it GRASS texts will be in selected language,
  799. # system messages (i.e. OK, Cancel etc.) - in system default
  800. # language
  801. os.environ['LANGUAGE'] = language
  802. return
  803. # Set up environment for subprocesses
  804. os.environ['LANGUAGE'] = language
  805. os.environ['LANG'] = language
  806. if encoding:
  807. normalized = locale.normalize('%s.%s' % (language, encoding))
  808. else:
  809. normalized = language
  810. for lc in ('LC_CTYPE', 'LC_MESSAGES', 'LC_TIME', 'LC_COLLATE',
  811. 'LC_MONETARY', 'LC_PAPER', 'LC_NAME', 'LC_ADDRESS',
  812. 'LC_TELEPHONE', 'LC_MEASUREMENT', 'LC_IDENTIFICATION'):
  813. os.environ[lc] = normalized
  814. # Some code in GRASS might not like other decimal separators than .
  815. # Other potential sources for problems are: LC_TIME LC_CTYPE
  816. locale.setlocale(locale.LC_NUMERIC, 'C')
  817. os.environ['LC_NUMERIC'] = 'C'
  818. if os.getenv('LC_ALL'):
  819. del os.environ['LC_ALL'] # Remove LC_ALL to not override LC_NUMERIC
  820. # From now on enforce the new language
  821. if encoding:
  822. gettext.install('grasslibs', gpath('locale'), codeset=encoding)
  823. else:
  824. gettext.install('grasslibs', gpath('locale'))
  825. def check_lock(force_gislock_removal):
  826. global lockfile
  827. if not os.path.exists(location):
  828. fatal(_("Path '%s' doesn't exist") % location)
  829. # Check for concurrent use
  830. lockfile = os.path.join(location, ".gislock")
  831. ret = call([gpath("etc", "lock"), lockfile, "%d" % os.getpid()])
  832. msg = None
  833. if ret == 2:
  834. if not force_gislock_removal:
  835. msg = _("%(user)s is currently running GRASS in selected mapset (" \
  836. "file %(file)s found). Concurrent use not allowed.\nYou can force launching GRASS using -f flag " \
  837. "(note that you need permission for this operation). Have another look in the processor " \
  838. "manager just to be sure..." % {
  839. 'user': user, 'file': lockfile})
  840. else:
  841. try_remove(lockfile)
  842. message(_("%(user)s is currently running GRASS in selected mapset (" \
  843. "file %(file)s found). Forcing to launch GRASS..." % {
  844. 'user': user, 'file': lockfile}))
  845. elif ret != 0:
  846. msg = _("Unable to properly access '%s'.\n"
  847. "Please notify system personel.") % lockfile
  848. if msg:
  849. if grass_gui == "wxpython":
  850. call([os.getenv('GRASS_PYTHON'), wxpath("gis_set_error.py"), msg])
  851. else:
  852. global remove_lockfile
  853. remove_lockfile = False
  854. fatal(msg)
  855. def make_fontcap():
  856. fc = os.getenv('GRASS_FONT_CAP')
  857. if fc and not os.access(fc, os.R_OK):
  858. message(_("Building user fontcap..."))
  859. call(["g.mkfontcap"])
  860. def check_shell():
  861. global sh, shellname, grass_env_file
  862. # cygwin has many problems with the shell setup
  863. # below, so i hardcoded everything here.
  864. if sys.platform == 'cygwin':
  865. sh = "cygwin"
  866. shellname = "GNU Bash (Cygwin)"
  867. os.environ['SHELL'] = "/usr/bin/bash.exe"
  868. os.environ['OSTYPE'] = "cygwin"
  869. else:
  870. # in docker the 'SHELL' variable may not be
  871. # visible in a Python session
  872. try:
  873. sh = os.path.basename(os.getenv('SHELL'))
  874. except:
  875. sh = 'sh'
  876. os.environ['SHELL'] = sh
  877. if windows and sh:
  878. sh = os.path.splitext(sh)[0]
  879. if sh == "ksh":
  880. shellname = "Korn Shell"
  881. elif sh == "csh":
  882. shellname = "C Shell"
  883. elif sh == "tcsh":
  884. shellname = "TC Shell"
  885. elif sh == "bash":
  886. shellname = "Bash Shell"
  887. elif sh == "sh":
  888. shellname = "Bourne Shell"
  889. elif sh == "zsh":
  890. shellname = "Z Shell"
  891. elif sh == "cmd":
  892. shellname = "Command Shell"
  893. else:
  894. shellname = "shell"
  895. if sh in ['csh', 'tcsh']:
  896. grass_env_file = os.path.join(grass_config_dir, 'cshrc')
  897. elif sh in ['bash', 'msh', 'cygwin', 'sh']:
  898. grass_env_file = os.path.join(grass_config_dir, 'bashrc')
  899. elif sh == 'zsh':
  900. grass_env_file = os.path.join(grass_config_dir, 'zshrc')
  901. elif sh == 'cmd':
  902. grass_env_file = os.path.join(grass_config_dir, 'env.bat')
  903. else:
  904. grass_env_file = os.path.join(grass_config_dir, 'bashrc')
  905. warning(_("Unsupported shell <%(sh)s>: %(env)s") % {'sh': sh,
  906. 'env': grass_env_file})
  907. # check for SHELL
  908. if not os.getenv('SHELL'):
  909. fatal(_("The SHELL variable is not set"))
  910. def get_batch_job():
  911. # hack to process batch jobs:
  912. return os.getenv('GRASS_BATCH_JOB')
  913. def run_batch_job(batch_job):
  914. batch_job_string = batch_job
  915. if not isinstance(batch_job, basestring):
  916. batch_job_string = ' '.join(batch_job)
  917. message(_("Executing <%s> ...") % batch_job_string)
  918. if isinstance(batch_job, basestring):
  919. proc = Popen(batch_job, shell=True)
  920. else:
  921. try:
  922. proc = Popen(batch_job, shell=False)
  923. except OSError as error:
  924. fatal(_("Execution of <{cmd}> failed:\n"
  925. "{error}").format(cmd=batch_job_string, error=error))
  926. returncode = proc.wait()
  927. message(_("Execution of <%s> finished.") % batch_job_string)
  928. return returncode
  929. def start_gui(grass_gui):
  930. # Start the chosen GUI but ignore text
  931. debug("GRASS GUI should be <%s>" % grass_gui)
  932. # Check for gui interface
  933. if grass_gui == "wxpython":
  934. Popen([os.getenv('GRASS_PYTHON'), wxpath("wxgui.py")])
  935. def clear_screen():
  936. global windows
  937. if windows:
  938. pass
  939. # TODO: uncomment when PDCurses works.
  940. # cls
  941. else:
  942. if not is_debug():
  943. call(["tput", "clear"])
  944. def show_banner():
  945. sys.stderr.write(r"""
  946. __________ ___ __________ _______________
  947. / ____/ __ \/ | / ___/ ___/ / ____/ _/ ___/
  948. / / __/ /_/ / /| | \__ \\_ \ / / __ / / \__ \
  949. / /_/ / _, _/ ___ |___/ /__/ / / /_/ // / ___/ /
  950. \____/_/ |_/_/ |_/____/____/ \____/___//____/
  951. """)
  952. def say_hello():
  953. sys.stderr.write(_("Welcome to GRASS GIS %s") % grass_version)
  954. if grass_version.endswith('svn'):
  955. try:
  956. filerev = open(gpath('etc', 'VERSIONNUMBER'))
  957. linerev = filerev.readline().rstrip('\n')
  958. filerev.close()
  959. revision = linerev.split(' ')[1]
  960. sys.stderr.write(' (' + revision + ')')
  961. except:
  962. pass
  963. def show_info():
  964. sys.stderr.write(
  965. r"""
  966. %-41shttp://grass.osgeo.org
  967. %-41s%s (%s)
  968. %-41sg.manual -i
  969. %-41sg.version -c
  970. """ % (_("GRASS GIS homepage:"),
  971. _("This version running through:"),
  972. shellname, os.getenv('SHELL'),
  973. _("Help is available with the command:"),
  974. _("See the licence terms with:")))
  975. if grass_gui == 'wxpython':
  976. message("%-41sg.gui wxpython" % _("If required, restart the GUI with:"))
  977. else:
  978. message("%-41sg.gui %s" % (_("Start the GUI with:"), default_gui))
  979. message("%-41sexit" % _("When ready to quit enter:"))
  980. message("")
  981. def csh_startup():
  982. global exit_val
  983. userhome = os.getenv('HOME') # save original home
  984. home = location
  985. os.environ['HOME'] = home
  986. cshrc = os.path.join(home, ".cshrc")
  987. tcshrc = os.path.join(home, ".tcshrc")
  988. try_remove(cshrc)
  989. try_remove(tcshrc)
  990. f = open(cshrc, 'w')
  991. f.write("set home = %s\n" % userhome)
  992. f.write("set history = 3000 savehist = 3000 noclobber ignoreeof\n")
  993. f.write("set histfile = %s\n" % os.path.join(os.getenv('HOME'),
  994. ".history"))
  995. f.write("set prompt = '\\\n")
  996. f.write("Mapset <%s> in Location <%s> \\\n" % (mapset, location_name))
  997. f.write("GRASS GIS %s > '\n" % grass_version)
  998. f.write("set BOGUS=``;unset BOGUS\n")
  999. path = os.path.join(userhome, ".grass.cshrc") # left for backward compatibility
  1000. if os.access(path, os.R_OK):
  1001. f.write(readfile(path) + '\n')
  1002. if os.access(grass_env_file, os.R_OK):
  1003. f.write(readfile(grass_env_file) + '\n')
  1004. mail_re = re.compile(r"^ *set *mail *= *")
  1005. for filename in [".cshrc", ".tcshrc", ".login"]:
  1006. path = os.path.join(userhome, filename)
  1007. if os.access(path, os.R_OK):
  1008. s = readfile(path)
  1009. lines = s.splitlines()
  1010. for l in lines:
  1011. if mail_re.match(l):
  1012. f.write(l)
  1013. path = os.getenv('PATH').split(':')
  1014. f.write("set path = ( %s ) \n" % ' '.join(path))
  1015. f.close()
  1016. writefile(tcshrc, readfile(cshrc))
  1017. exit_val = call([gpath("etc", "run"), os.getenv('SHELL')])
  1018. os.environ['HOME'] = userhome
  1019. def bash_startup():
  1020. global exit_val
  1021. # save command history in mapset dir and remember more
  1022. os.environ['HISTFILE'] = os.path.join(location, ".bash_history")
  1023. if not os.getenv('HISTSIZE') and not os.getenv('HISTFILESIZE'):
  1024. os.environ['HISTSIZE'] = "3000"
  1025. # instead of changing $HOME, start bash with: --rcfile "$LOCATION/.bashrc" ?
  1026. # if so, must care be taken to explicity call .grass.bashrc et al for
  1027. # non-interactive bash batch jobs?
  1028. userhome = os.getenv('HOME') # save original home
  1029. home = location # save .bashrc in $LOCATION
  1030. os.environ['HOME'] = home
  1031. bashrc = os.path.join(home, ".bashrc")
  1032. try_remove(bashrc)
  1033. f = open(bashrc, 'w')
  1034. f.write("test -r ~/.alias && . ~/.alias\n")
  1035. if os.getenv('ISISROOT'):
  1036. f.write("PS1='ISIS-GRASS %s (%s):\w > '\n" % (grass_version, location_name))
  1037. else:
  1038. f.write("PS1='GRASS %s (%s):\w > '\n" % (grass_version, location_name))
  1039. f.write("""grass_prompt() {
  1040. LOCATION="`g.gisenv get=GISDBASE,LOCATION_NAME,MAPSET separator='/'`"
  1041. if test -d "$LOCATION/grid3/G3D_MASK" && test -f "$LOCATION/cell/MASK" ; then
  1042. echo [%s]
  1043. elif test -f "$LOCATION/cell/MASK" ; then
  1044. echo [%s]
  1045. elif test -d "$LOCATION/grid3/G3D_MASK" ; then
  1046. echo [%s]
  1047. fi
  1048. }
  1049. PROMPT_COMMAND=grass_prompt\n""" % (_("2D and 3D raster MASKs present"),
  1050. _("Raster MASK present"),
  1051. _("3D raster MASK present")))
  1052. # read environmental variables
  1053. path = os.path.join(userhome, ".grass.bashrc") # left for backward compatibility
  1054. if os.access(path, os.R_OK):
  1055. f.write(readfile(path) + '\n')
  1056. if os.access(grass_env_file, os.R_OK):
  1057. f.write(readfile(grass_env_file) + '\n')
  1058. f.write("export PATH=\"%s\"\n" % os.getenv('PATH'))
  1059. f.write("export HOME=\"%s\"\n" % userhome) # restore user home path
  1060. f.close()
  1061. exit_val = call([gpath("etc", "run"), os.getenv('SHELL')])
  1062. os.environ['HOME'] = userhome
  1063. def default_startup():
  1064. global exit_val
  1065. if windows:
  1066. os.environ['PS1'] = "GRASS %s> " % (grass_version)
  1067. # "$ETC/run" doesn't work at all???
  1068. exit_val = subprocess.call([os.getenv('SHELL')])
  1069. cleanup_dir(os.path.join(location, ".tmp")) # remove GUI session files from .tmp
  1070. else:
  1071. os.environ['PS1'] = "GRASS %s (%s):\w > " % (grass_version, location_name)
  1072. exit_val = call([gpath("etc", "run"), os.getenv('SHELL')])
  1073. if exit_val != 0:
  1074. fatal(_("Failed to start shell '%s'") % os.getenv('SHELL'))
  1075. def done_message():
  1076. # here was something for batch job but it was never called
  1077. message(_("Done."))
  1078. message("")
  1079. message(_("Goodbye from GRASS GIS"))
  1080. message("")
  1081. def clean_temp():
  1082. message(_("Cleaning up temporary files..."))
  1083. nul = open(os.devnull, 'w')
  1084. call([gpath("etc", "clean_temp")], stdout=nul)
  1085. nul.close()
  1086. def grep(string,list):
  1087. expr = re.compile(string)
  1088. return [elem for elem in list if expr.match(elem)]
  1089. def print_params():
  1090. plat = gpath('include', 'Make', 'Platform.make')
  1091. if not os.path.exists(plat):
  1092. fatal(_("Please install the GRASS GIS development package"))
  1093. fileplat = open(plat)
  1094. linesplat = fileplat.readlines()
  1095. fileplat.close()
  1096. params = sys.argv[2:]
  1097. if not params:
  1098. params = ['arch', 'build', 'compiler', 'path', 'revision']
  1099. for arg in params:
  1100. if arg == 'path':
  1101. sys.stdout.write("%s\n" % gisbase)
  1102. elif arg == 'arch':
  1103. val = grep('ARCH',linesplat)
  1104. sys.stdout.write("%s\n" % val[0].split('=')[1].strip())
  1105. elif arg == 'build':
  1106. build = gpath('include', 'grass', 'confparms.h')
  1107. filebuild = open(build)
  1108. val = filebuild.readline()
  1109. filebuild.close()
  1110. sys.stdout.write("%s\n" % val.strip().strip('"').strip())
  1111. elif arg == 'compiler':
  1112. val = grep('CC',linesplat)
  1113. sys.stdout.write("%s\n" % val[0].split('=')[1].strip())
  1114. elif arg == 'revision':
  1115. rev = gpath('include', 'grass', 'gis.h')
  1116. filerev = open(rev)
  1117. linesrev = filerev.readlines()
  1118. val = grep('#define GIS_H_VERSION', linesrev)
  1119. filerev.close()
  1120. sys.stdout.write("%s\n" % val[0].split(':')[1].rstrip('$"\n').strip())
  1121. else:
  1122. message(_("Parameter <%s> not supported") % arg)
  1123. def get_username():
  1124. """Get name of the current user"""
  1125. if windows:
  1126. user = os.getenv('USERNAME')
  1127. if not user:
  1128. user = "user_name"
  1129. else:
  1130. user = os.getenv('USER')
  1131. if not user:
  1132. user = os.getenv('LOGNAME')
  1133. if not user:
  1134. try:
  1135. p = Popen(['whoami'], stdout = subprocess.PIPE)
  1136. s = p.stdout.read()
  1137. p.wait()
  1138. user = s.strip()
  1139. except:
  1140. pass
  1141. if not user:
  1142. user = "user_%d" % os.getuid()
  1143. return user
  1144. class Parameters:
  1145. # we don't need to define any methods
  1146. # pylint: disable=R0903
  1147. def __init__(self):
  1148. self.grass_gui = None
  1149. self.create_new = None
  1150. self.exit_grass = None
  1151. self.force_gislock_removal = None
  1152. self.mapset = None
  1153. self.geofile = None
  1154. def parse_cmdline(argv):
  1155. params = Parameters()
  1156. args = []
  1157. for i in argv:
  1158. # Check if the user asked for the version
  1159. if i in ["-v", "--version"]:
  1160. message("GRASS GIS %s" % grass_version)
  1161. message('\n' + readfile(gpath("etc", "license")))
  1162. sys.exit()
  1163. # Check if the user asked for help
  1164. elif i in ["help", "-h", "-help", "--help", "--h"]:
  1165. help_message()
  1166. sys.exit()
  1167. # Check if the -text flag was given
  1168. elif i in ["-text", "--text"]:
  1169. params.grass_gui = 'text'
  1170. # Check if the -gtext flag was given
  1171. elif i in ["-gtext", "--gtext"]:
  1172. params.grass_gui = 'gtext'
  1173. # Check if the -gui flag was given
  1174. elif i in ["-gui", "--gui"]:
  1175. params.grass_gui = default_gui
  1176. # Check if the -wxpython flag was given
  1177. elif i in ["-wxpython", "-wx", "--wxpython", "--wx"]:
  1178. params.grass_gui = 'wxpython'
  1179. # Check if the user wants to create a new mapset
  1180. elif i == "-c":
  1181. params.create_new = True
  1182. elif i == "-e":
  1183. params.exit_grass = True
  1184. elif i == "-f":
  1185. params.force_gislock_removal = True
  1186. elif i == "--config":
  1187. print_params()
  1188. sys.exit()
  1189. else:
  1190. args.append(i)
  1191. if len(args) > 1:
  1192. params.mapset = args[1]
  1193. params.geofile = args[0]
  1194. elif len(args) == 1:
  1195. params.mapset = args[0]
  1196. else:
  1197. params.mapset = None
  1198. return params
  1199. ### MAIN script starts here
  1200. # Get the system name
  1201. windows = sys.platform == 'win32'
  1202. cygwin = "cygwin" in sys.platform
  1203. macosx = "darwin" in sys.platform
  1204. ### commented-out: broken winGRASS
  1205. # if 'GISBASE' in os.environ:
  1206. # sys.exit(_("ERROR: GRASS GIS is already running "
  1207. # "(environmental variable GISBASE found)"))
  1208. # this is not really an issue, we should be able to overpower another session
  1209. # Set GISBASE
  1210. os.environ['GISBASE'] = gisbase
  1211. # set HOME
  1212. if windows and not os.getenv('HOME'):
  1213. os.environ['HOME'] = os.path.join(os.getenv('HOMEDRIVE'),
  1214. os.getenv('HOMEPATH'))
  1215. # set SHELL
  1216. if windows:
  1217. if os.getenv('GRASS_SH'):
  1218. os.environ['SHELL'] = os.getenv('GRASS_SH')
  1219. if not os.getenv('SHELL'):
  1220. os.environ['SHELL'] = os.getenv('COMSPEC', 'cmd.exe')
  1221. # Set default GUI
  1222. default_gui = "wxpython"
  1223. # explain what is happening in debug mode
  1224. debug("GRASS_DEBUG environmental variable is set. It is meant to be"
  1225. " an internal variable for debugging only this script.\n"
  1226. " Use 'g.gisenv set=\"DEBUG=[0-5]\"'"
  1227. " to turn GRASS GIS debug mode on if you wish to do so.")
  1228. # Set GRASS version number for R interface etc (must be an env_var for MS-Windows)
  1229. os.environ['GRASS_VERSION'] = grass_version
  1230. # Set the GIS_LOCK variable to current process id
  1231. gis_lock = str(os.getpid())
  1232. os.environ['GIS_LOCK'] = gis_lock
  1233. if not os.path.exists(grass_config_dir):
  1234. os.mkdir(grass_config_dir)
  1235. batch_job = get_batch_job()
  1236. # variable defined, but user might not have been careful enough
  1237. if batch_job:
  1238. if not os.access(batch_job, os.F_OK):
  1239. # wrong file
  1240. fatal(_("Job file <%s> has been defined in "
  1241. "the 'GRASS_BATCH_JOB' variable but not found. Exiting.\n\n"
  1242. "Use 'unset GRASS_BATCH_JOB' to disable batch job processing.") % batch_job)
  1243. elif not os.access(batch_job, os.X_OK):
  1244. # right file, but ...
  1245. fatal(_("Change file permission to 'executable' for <%s>") % batch_job)
  1246. # Set the global grassrc file
  1247. if batch_job:
  1248. gisrcrc = os.path.join(grass_config_dir, "rc.%s" % platform.node())
  1249. if not os.access(gisrcrc, os.R_OK):
  1250. gisrcrc = os.path.join(grass_config_dir, "rc")
  1251. else:
  1252. gisrcrc = os.path.join(grass_config_dir, "rc")
  1253. # Parse the command-line options and set several global variables
  1254. BATCH_EXEC_SUBCOMMAND = 'exec'
  1255. try:
  1256. # raises ValueError when not found
  1257. index = sys.argv.index(BATCH_EXEC_SUBCOMMAND)
  1258. batch_job = sys.argv[index + 1:]
  1259. clean_argv = sys.argv[1:index]
  1260. params = parse_cmdline(clean_argv)
  1261. except ValueError:
  1262. params = parse_cmdline(sys.argv[1:])
  1263. grass_gui = params.grass_gui
  1264. if params.exit_grass and not params.create_new:
  1265. fatal(_("Flag -e requires also flag -c"))
  1266. # Set the username
  1267. user = get_username()
  1268. # Set language
  1269. # This has to be called before any _() function call!
  1270. # Subsequent functions are using _() calls and
  1271. # thus must be called only after Language has been set.
  1272. set_language()
  1273. # Create the temporary directory and session grassrc file
  1274. tmpdir = create_tmp(user, gis_lock)
  1275. atexit.register(cleanup, tmpdir)
  1276. # Create the session grassrc file
  1277. gisrc = create_gisrc(tmpdir, gisrcrc)
  1278. # Set shell (needs to be called before load_env())
  1279. check_shell()
  1280. # Load environmental variables from the file
  1281. load_env()
  1282. # Ensure GUI is set
  1283. if batch_job:
  1284. grass_gui = 'text'
  1285. elif not grass_gui:
  1286. # if GUI was not set previously (e.g. command line),
  1287. # get it from rc file or env variable
  1288. grass_gui = read_gui(default_gui)
  1289. # Set PATH, PYTHONPATH
  1290. set_paths()
  1291. # Set LD_LIBRARY_PATH (etc) to find GRASS shared libraries
  1292. path_prepend(gpath("lib"), ld_library_path_var)
  1293. # Set GRASS_PAGER, GRASS_PYTHON, GRASS_GNUPLOT, GRASS_PROJSHARE
  1294. set_defaults()
  1295. # Set GRASS_HTML_BROWSER
  1296. set_browser()
  1297. #predefine monitor size for certain architectures
  1298. if os.getenv('HOSTTYPE') == 'arm':
  1299. # small monitor on ARM (iPAQ, zaurus... etc)
  1300. os.environ['GRASS_RENDER_HEIGHT'] = "320"
  1301. os.environ['GRASS_RENDER_WIDTH'] = "240"
  1302. # First time user - GISRC is defined in the GRASS script
  1303. if not os.access(gisrc, os.F_OK):
  1304. if grass_gui == 'text' and not params.mapset:
  1305. fatal(_("Unable to start GRASS GIS. You have the choice to:\n"
  1306. " - Launch the GRASS GIS interface with the '-gui' switch (`%s -gui`)\n"
  1307. " - Launch GRASS GIS directly with path to "
  1308. "the location/mapset as an argument (`%s /path/to/location/mapset`)\n"
  1309. " - Create manually the GISRC file (%s)") % (cmd_name, cmd_name, gisrcrc))
  1310. create_initial_gisrc(gisrc)
  1311. else:
  1312. clean_temp()
  1313. if params.create_new:
  1314. message(_("Creating new GRASS GIS location/mapset..."))
  1315. else:
  1316. message(_("Starting GRASS GIS..."))
  1317. # check that the GUI works but only if not doing a batch job
  1318. if not batch_job:
  1319. grass_gui = check_gui(expected_gui=grass_gui)
  1320. save_gui(gisrc, grass_gui)
  1321. # Parsing argument to get LOCATION
  1322. if not params.mapset:
  1323. # Try interactive startup
  1324. # User selects LOCATION and MAPSET if not set
  1325. set_mapset_interactive(grass_gui)
  1326. else:
  1327. if params.create_new and params.geofile:
  1328. set_mapset(params.mapset, params.geofile, create_new=True)
  1329. else:
  1330. set_mapset(params.mapset, create_new=params.create_new)
  1331. # Set GISDBASE, LOCATION_NAME, MAPSET, LOCATION from $GISRC
  1332. # e.g. wxGUI startup screen writes to the gisrc file,
  1333. # so loading it is the only universal way to obtain the values
  1334. # this suppose that both programs share the right path to gisrc file
  1335. load_gisrc(gisrc)
  1336. # Check .gislock file
  1337. check_lock(params.force_gislock_removal)
  1338. # build user fontcap if specified but not present
  1339. make_fontcap()
  1340. # predefine default driver if DB connection not defined
  1341. # is this really needed?? Modules should call this when/if required.
  1342. if not os.access(os.path.join(location, "VAR"), os.F_OK):
  1343. call(['db.connect', '-c', '--quiet'])
  1344. # Display the version and license info
  1345. # only non-error, interactive version continues from here
  1346. if batch_job:
  1347. returncode = run_batch_job(batch_job)
  1348. clean_temp()
  1349. try_remove(lockfile)
  1350. sys.exit(returncode)
  1351. elif params.exit_grass:
  1352. clean_temp()
  1353. try_remove(lockfile)
  1354. sys.exit(0)
  1355. else:
  1356. start_gui(grass_gui)
  1357. clear_screen()
  1358. show_banner()
  1359. say_hello()
  1360. show_info()
  1361. if grass_gui == "wxpython":
  1362. message(_("Launching <%s> GUI in the background, please wait...") % grass_gui)
  1363. if sh in ['csh', 'tcsh']:
  1364. csh_startup()
  1365. elif sh in ['bash', 'msh', 'cygwin']:
  1366. bash_startup()
  1367. else:
  1368. default_startup()
  1369. # here we are at the end of grass session
  1370. clear_screen()
  1371. clean_temp()
  1372. try_remove(lockfile)
  1373. # save 'last used' GISRC after removing variables which shouldn't be saved
  1374. clean_env(gisrc)
  1375. writefile(gisrcrc, readfile(gisrc))
  1376. # here was cleanup function call but it is already registered at exit
  1377. # After this point no more grass modules may be called
  1378. done_message()