grass.py 51 KB

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