grass.py 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189
  1. #!/usr/bin/env python
  2. #############################################################################
  3. #
  4. # MODULE: GRASS initialization (Python)
  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. # Converted to Python (based on init.sh) by Glynn Clements
  12. # Martin Landa <landa.martin gmail.com>
  13. # Luca Delucchi <lucadeluge@gmail.com>
  14. # PURPOSE: Sets up environment variables, parses any remaining
  15. # command line options for setting the GISDBASE, LOCATION,
  16. # and/or MAPSET. Finally it starts GRASS with the appropriate user
  17. # interface and cleans up after it is finished.
  18. # COPYRIGHT: (C) 2000-2011 by the GRASS Development Team
  19. #
  20. # This program is free software under the GNU General
  21. # Public License (>=v2). Read the file COPYING that
  22. # comes with GRASS for details.
  23. #
  24. #############################################################################
  25. import sys
  26. import os
  27. import atexit
  28. import string
  29. import subprocess
  30. import re
  31. import platform
  32. # Variables substituted during build process
  33. if os.environ.has_key('GISBASE'):
  34. gisbase = os.environ['GISBASE']
  35. else:
  36. gisbase = "@GISBASE@"
  37. cmd_name = "@START_UP@"
  38. grass_version = "@GRASS_VERSION_NUMBER@"
  39. ld_library_path_var = '@LD_LIBRARY_PATH_VAR@'
  40. if os.environ.has_key('GRASS_PROJSHARE'):
  41. config_projshare = os.environ['GRASS_PROJSHARE']
  42. else:
  43. config_projshare = "@CONFIG_PROJSHARE@"
  44. # configuration directory
  45. if sys.platform == 'win32':
  46. grass_config_dirname = "GRASS7"
  47. grass_config_dir = os.path.join(os.getenv('APPDATA'), grass_config_dirname)
  48. else:
  49. grass_config_dirname = ".grass7"
  50. grass_config_dir = os.path.join(os.getenv('HOME'), grass_config_dirname)
  51. gisbase = os.path.normpath(gisbase)
  52. # i18N
  53. import gettext
  54. gettext.install('grasslibs', os.path.join(gisbase, 'locale'), unicode = True)
  55. tmpdir = None
  56. lockfile = None
  57. remove_lockfile = True
  58. location = None
  59. create_new = None
  60. grass_gui = None
  61. def warning(text):
  62. sys.stderr.write(_("WARNING") + ': ' + text + os.linesep)
  63. def try_remove(path):
  64. try:
  65. os.remove(path)
  66. except:
  67. pass
  68. def try_rmdir(path):
  69. try:
  70. os.rmdir(path)
  71. except:
  72. pass
  73. def clean_env():
  74. env_curr = read_gisrc()
  75. env_new = {}
  76. for k,v in env_curr.iteritems():
  77. if 'MONITOR' not in k:
  78. env_new[k] = v
  79. write_gisrc(env_new)
  80. def cleanup_dir(path):
  81. if not path:
  82. return
  83. for root, dirs, files in os.walk(path, topdown = False):
  84. for name in files:
  85. try_remove(os.path.join(root, name))
  86. for name in dirs:
  87. try_rmdir(os.path.join(root, name))
  88. def cleanup():
  89. tmpdir, lockfile, remove_lockfile
  90. # all exits after setting up $tmpdir should also tidy it up
  91. cleanup_dir(tmpdir)
  92. try_rmdir(tmpdir)
  93. if lockfile and remove_lockfile:
  94. try_remove(lockfile)
  95. def fatal(msg):
  96. sys.exit(msg)
  97. def message(msg):
  98. sys.stderr.write(msg + "\n")
  99. sys.stderr.flush()
  100. def readfile(path):
  101. f = open(path, 'r')
  102. s = f.read()
  103. f.close()
  104. return s
  105. def writefile(path, s):
  106. f = open(path, 'w')
  107. f.write(s)
  108. f.close()
  109. def call(cmd, **kwargs):
  110. if windows:
  111. kwargs['shell'] = True
  112. return subprocess.call(cmd, **kwargs)
  113. def Popen(cmd, **kwargs):
  114. if windows:
  115. kwargs['shell'] = True
  116. return subprocess.Popen(cmd, **kwargs)
  117. def gfile(*args):
  118. return os.path.join(gisbase, *args)
  119. help_text = r"""
  120. %s:
  121. $CMD_NAME [-h | -help | --help] [-v | --version] [-c | -c geofile | -c EPSG:code]
  122. [-text | -gui] [--config param]
  123. [[[<GISDBASE>/]<LOCATION_NAME>/]<MAPSET>]
  124. %s:
  125. -h or -help or --help %s
  126. -v or --version %s
  127. -c %s
  128. -text %s
  129. %s
  130. -gui %s
  131. %s
  132. --config %s
  133. %s
  134. %s:
  135. GISDBASE %s
  136. LOCATION_NAME %s
  137. MAPSET %s
  138. GISDBASE/LOCATION_NAME/MAPSET %s
  139. %s:
  140. GRASS_GUI %s
  141. GRASS_WISH %s
  142. GRASS_HTML_BROWSER %s
  143. GRASS_ADDON_PATH %s
  144. GRASS_ADDON_BASE %s
  145. GRASS_BATCH_JOB %s
  146. GRASS_PYTHON %s
  147. """ % (_("Usage"),
  148. _("Flags"),
  149. _("print this help message"),
  150. _("show version information and exit"),
  151. _("create given database, location or mapset if it doesn't exist"),
  152. _("use text based interface"),
  153. _("and set as default"),
  154. _("use $DEFAULT_GUI graphical user interface"),
  155. _("and set as default"),
  156. _("print GRASS configuration parameters"),
  157. _("options: arch,build,compiler,path,revision"),
  158. _("Parameters"),
  159. _("initial database (path to GIS data)"),
  160. _("initial location"),
  161. _("initial mapset"),
  162. _("fully qualified initial mapset directory"),
  163. _("Environment variables relevant for startup"),
  164. _("select GUI (text, gui)"),
  165. _("set wish shell name to override 'wish'"),
  166. _("set html web browser for help pages"),
  167. _("set additional path(s) to local GRASS modules or user scripts"),
  168. _("set additional GISBASE for locally installed GRASS Addons"),
  169. _("shell script to be processed as batch job"),
  170. _("set python shell name to override 'python'"))
  171. def help_message():
  172. t = string.Template(help_text)
  173. s = t.substitute(CMD_NAME = cmd_name, DEFAULT_GUI = default_gui)
  174. sys.stderr.write(s)
  175. def create_tmp():
  176. global tmpdir
  177. ## use $TMPDIR if it exists, then $TEMP, otherwise /tmp
  178. tmp = os.getenv('TMPDIR')
  179. if not tmp:
  180. tmp = os.getenv('TEMP')
  181. if not tmp:
  182. tmp = '/tmp'
  183. tmpdir = os.path.join(tmp, "grass7-%s-%s" % (user, gis_lock))
  184. try:
  185. os.mkdir(tmpdir, 0700)
  186. except:
  187. fatal(_("Unable to create temporary directory <%s>! Exiting.") % tmpdir)
  188. def create_gisrc():
  189. global gisrc, gisrcrc
  190. # Set the session grassrc file
  191. gisrc = os.path.join(tmpdir, "gisrc")
  192. os.environ['GISRC'] = gisrc
  193. # remove invalid GISRC file to avoid disturbing error messages:
  194. try:
  195. s = readfile(gisrcrc)
  196. if "UNKNOWN" in s:
  197. try_remove(gisrcrc)
  198. s = None
  199. except:
  200. s = None
  201. # Copy the global grassrc file to the session grassrc file
  202. if s:
  203. writefile(gisrc, s)
  204. def read_gisrc():
  205. kv = {}
  206. try:
  207. f = open(gisrc, 'r')
  208. except IOError:
  209. return kv
  210. for line in f:
  211. k, v = line.split(':', 1)
  212. kv[k.strip()] = v.strip()
  213. f.close()
  214. return kv
  215. def read_env_file(path):
  216. kv = {}
  217. f = open(path, 'r')
  218. for line in f:
  219. k, v = line.split(':', 1)
  220. kv[k.strip()] = v.strip()
  221. f.close()
  222. return kv
  223. def write_gisrc(kv):
  224. f = open(gisrc, 'w')
  225. for k, v in kv.iteritems():
  226. f.write("%s: %s\n" % (k, v))
  227. f.close()
  228. def read_gui():
  229. global grass_gui
  230. # At this point the GRASS user interface variable has been set from the
  231. # command line, been set from an external environment variable, or is
  232. # not set. So we check if it is not set
  233. if not grass_gui:
  234. # Check for a reference to the GRASS user interface in the grassrc file
  235. if os.access(gisrc, os.R_OK):
  236. kv = read_gisrc()
  237. if 'GRASS_GUI' in os.environ:
  238. grass_gui = os.environ['GRASS_GUI']
  239. elif 'GUI' in kv:
  240. grass_gui = kv['GUI']
  241. elif 'GRASS_GUI' in kv:
  242. # For backward compatibility (GRASS_GUI renamed to GUI)
  243. grass_gui = kv['GRASS_GUI']
  244. else:
  245. # Set the GRASS user interface to the default if needed
  246. grass_gui = default_gui
  247. if not grass_gui:
  248. grass_gui = default_gui
  249. if grass_gui == 'gui':
  250. grass_gui = default_gui
  251. # FIXME oldtcltk, gis.m, d.m no longer exist
  252. if grass_gui in ['d.m', 'gis.m', 'oldtcltk', 'tcltk']:
  253. warning(_("GUI <%s> not supported in this version") % grass_gui)
  254. grass_gui = default_gui
  255. def get_locale():
  256. global locale
  257. locale = None
  258. for var in ['LC_ALL', 'LC_MESSAGES', 'LANG', 'LANGUAGE']:
  259. loc = os.getenv(var)
  260. if loc:
  261. locale = loc[0:2]
  262. return
  263. def path_prepend(dir, var):
  264. path = os.getenv(var)
  265. if path:
  266. path = dir + os.pathsep + path
  267. else:
  268. path = dir
  269. os.environ[var] = path
  270. def path_append(dir, var):
  271. path = os.getenv(var)
  272. if path:
  273. path = path + os.pathsep + dir
  274. else:
  275. path = dir
  276. os.environ[var] = path
  277. def set_paths():
  278. # addons (path)
  279. addon_path = os.getenv('GRASS_ADDON_PATH')
  280. if addon_path:
  281. for path in addon_path.split(os.pathsep):
  282. path_prepend(addon_path, 'PATH')
  283. # addons (base)
  284. addon_base = os.getenv('GRASS_ADDON_BASE')
  285. if not addon_base:
  286. addon_base = os.path.join(grass_config_dir, 'addons')
  287. os.environ['GRASS_ADDON_BASE'] = addon_base
  288. path_prepend(os.path.join(addon_base, 'scripts'), 'PATH')
  289. path_prepend(os.path.join(addon_base, 'bin'), 'PATH')
  290. # standard installation
  291. path_prepend(gfile('scripts'), 'PATH')
  292. path_prepend(gfile('bin'), 'PATH')
  293. # Set PYTHONPATH to find GRASS Python modules
  294. path_prepend(gfile('etc', 'python'), 'PYTHONPATH')
  295. # set path for the GRASS man pages
  296. grass_man_path = os.path.join(gisbase, 'docs', 'man')
  297. addons_man_path = os.path.join(addon_base, 'docs', 'man')
  298. man_path = os.getenv('MANPATH')
  299. if man_path:
  300. path_prepend(addons_man_path, 'MANPATH')
  301. path_prepend(grass_man_path, 'MANPATH')
  302. else:
  303. try:
  304. p = Popen(['manpath'], stdout = subprocess.PIPE)
  305. s = p.stdout.read()
  306. p.wait()
  307. sys_man_path = s.strip()
  308. except:
  309. pass
  310. if sys_man_path:
  311. os.environ['MANPATH'] = sys_man_path
  312. path_prepend(addons_man_path, 'MANPATH')
  313. path_prepend(grass_man_path, 'MANPATH')
  314. else:
  315. os.environ['MANPATH'] = addons_man_path
  316. path_prepend(os.path.join(grass_man_path, 'MANPATH'))
  317. # Add .py (Python) to list of executable extensions to search for
  318. # in MS-Windows PATH
  319. if windows:
  320. path_append('.PY', 'PATHEXT')
  321. def find_exe(pgm):
  322. for dir in os.getenv('PATH').split(os.pathsep):
  323. path = os.path.join(dir, pgm)
  324. if os.access(path, os.X_OK):
  325. return path
  326. return None
  327. def set_defaults():
  328. # GRASS_PAGER
  329. if not os.getenv('GRASS_PAGER'):
  330. if find_exe("more"):
  331. pager = "more"
  332. elif find_exe("less"):
  333. pager = "less"
  334. elif windows:
  335. pager = "more"
  336. else:
  337. pager = "cat"
  338. os.environ['GRASS_PAGER'] = pager
  339. # GRASS_WISH
  340. if not os.getenv('GRASS_WISH'):
  341. os.environ['GRASS_WISH'] = "wish"
  342. # GRASS_PYTHON
  343. if not os.getenv('GRASS_PYTHON'):
  344. if windows:
  345. os.environ['GRASS_PYTHON'] = "python.exe"
  346. else:
  347. os.environ['GRASS_PYTHON'] = "python"
  348. # GRASS_GNUPLOT
  349. if not os.getenv('GRASS_GNUPLOT'):
  350. os.environ['GRASS_GNUPLOT'] = "gnuplot -persist"
  351. # GRASS_PROJSHARE
  352. if not os.getenv('GRASS_PROJSHARE'):
  353. os.environ['GRASS_PROJSHARE'] = config_projshare
  354. def set_browser():
  355. # GRASS_HTML_BROWSER
  356. browser = os.getenv('GRASS_HTML_BROWSER')
  357. if not browser:
  358. if macosx:
  359. # OSX doesn't execute browsers from the shell PATH - route thru a script
  360. browser = gfile('etc', "html_browser_mac.sh")
  361. os.environ['GRASS_HTML_BROWSER_MACOSX'] = "-b com.apple.helpviewer"
  362. if windows or cygwin:
  363. # MinGW startup moved to into init.bat
  364. browser = "explorer"
  365. else:
  366. # the usual suspects
  367. browsers = [ "xdg-open", "htmlview", "konqueror", "mozilla", "mozilla-firefox",
  368. "firefox", "iceweasel", "opera", "netscape", "dillo", "lynx", "links", "w3c" ]
  369. for b in browsers:
  370. if find_exe(b):
  371. browser = b
  372. break
  373. elif macosx:
  374. # OSX doesn't execute browsers from the shell PATH - route thru a script
  375. os.environ['GRASS_HTML_BROWSER_MACOSX'] = "-b %s" % browser
  376. browser = gfile('etc', "html_browser_mac.sh")
  377. if not browser:
  378. warning(_("Searched for a web browser, but none found"))
  379. # even so we set konqueror to make lib/gis/parser.c happy:
  380. browser = "konqueror"
  381. os.environ['GRASS_HTML_BROWSER'] = browser
  382. def grass_intro():
  383. intro = r"""
  384. WELCOME TO GRASS %s
  385. 1) Have at your side all available GRASS tutorials
  386. 2) When working on your location, the following materials
  387. are extremely useful:
  388. - A topo map of your area
  389. - Current catalog of available computer maps
  390. 3) Check the GRASS webpages for feedback mailinglists and more:
  391. http://grass.osgeo.org
  392. http://www.grass-gis.org
  393. """ % grass_version
  394. sys.stderr.write(intro)
  395. sys.stderr.write("\n")
  396. sys.stderr.write(_("Hit RETURN to continue"))
  397. sys.stdin.readline()
  398. # for convenience, define pwd as GISDBASE:
  399. s = r"""GISDBASE: %s
  400. LOCATION_NAME: <UNKNOWN>
  401. MAPSET: <UNKNOWN>
  402. """ % os.getcwd()
  403. writefile(gisrc, s)
  404. def check_gui():
  405. global grass_gui, wxpython_base
  406. # Check if we are running X windows by checking the DISPLAY variable
  407. if os.getenv('DISPLAY') or windows:
  408. # Check if python is working properly
  409. if grass_gui == 'wxpython':
  410. nul = open(os.devnull, 'w')
  411. p = Popen([os.environ['GRASS_PYTHON']],
  412. stdin = subprocess.PIPE,
  413. stdout = nul, stderr = nul)
  414. nul.close()
  415. p.stdin.write("variable=True")
  416. p.stdin.close()
  417. p.wait()
  418. if p.returncode == 0:
  419. # Set the wxpython base directory
  420. wxpython_base = gfile("etc", "gui", "wxpython")
  421. else:
  422. # Python was not found - switch to text interface mode
  423. warning(_("The python command does not work as expected!\n"
  424. "Please check your GRASS_PYTHON environment variable.\n"
  425. "Use the -help option for details.\n"
  426. "Switching to text based interface mode.\n\n"
  427. "Hit RETURN to continue.\n"))
  428. sys.stdin.readline()
  429. grass_gui = 'text'
  430. else:
  431. # Display a message if a graphical interface was expected
  432. if grass_gui != 'text':
  433. # Set the interface mode to text
  434. warning(_("It appears that the X Windows system is not active.\n"
  435. "A graphical based user interface is not supported.\n"
  436. "Switching to text based interface mode.\n\n"
  437. "Hit RETURN to continue"""))
  438. sys.stdin.readline()
  439. grass_gui = 'text'
  440. # Save the user interface variable in the grassrc file - choose a temporary
  441. # file name that should not match another file
  442. if os.access(gisrc, os.F_OK):
  443. kv = read_gisrc()
  444. kv['GUI'] = grass_gui
  445. write_gisrc(kv)
  446. def non_interactive(arg, geofile = None):
  447. global gisdbase, location_name, mapset, location
  448. # Try non-interactive startup
  449. l = None
  450. if arg == '-':
  451. if location:
  452. l = location
  453. else:
  454. l = arg
  455. if l:
  456. if l == '.':
  457. l = os.getcwd()
  458. elif not os.path.isabs(l):
  459. l = os.path.abspath(l)
  460. l, mapset = os.path.split(l)
  461. if not mapset:
  462. l, mapset = os.path.split(l)
  463. l, location_name = os.path.split(l)
  464. gisdbase = l
  465. if gisdbase and location_name and mapset:
  466. location = os.path.join(gisdbase, location_name, mapset)
  467. if not os.access(os.path.join(location, "WIND"), os.R_OK):
  468. if location_name == "PERMANENT":
  469. fatal(_("<%s> is not a valid GRASS location") % location)
  470. else:
  471. # the user wants to create mapset on the fly
  472. if create_new:
  473. if not os.access(os.path.join(os.path.join(gisdbase, location_name,
  474. "PERMANENT", "DEFAULT_WIND")), os.F_OK):
  475. # create new location
  476. gisdbase = os.path.join(gisdbase, location_name)
  477. location_name = mapset
  478. mapset = "PERMANENT"
  479. if os.access(os.path.join(os.path.join(gisdbase, location_name,
  480. "PERMANENT", "DEFAULT_WIND")), os.F_OK):
  481. fatal(_("Failed to create new location. The location <%s> already exists." % location_name))
  482. sys.path.append(gfile('etc', 'python'))
  483. from grass.script import core as grass
  484. try:
  485. if geofile and geofile.find('EPSG:') > -1:
  486. epsg = geofile.split(':', 1)[1]
  487. grass.create_location(gisdbase, location_name, epsg = epsg)
  488. else:
  489. grass.create_location(gisdbase, location_name, filename = geofile)
  490. except grass.ScriptError, e:
  491. fatal(e.value.strip('"').strip("'").replace('\\n', os.linesep))
  492. else:
  493. # create new mapset
  494. os.mkdir(location)
  495. # copy PERMANENT/DEFAULT_WIND to <mapset>/WIND
  496. s = readfile(os.path.join(gisdbase, location_name, "PERMANENT", "DEFAULT_WIND"))
  497. writefile(os.path.join(location, "WIND"), s)
  498. message(_("Missing WIND file fixed"))
  499. else:
  500. fatal(_("<%s> is not a valid GRASS location") % location)
  501. if os.access(gisrc, os.R_OK):
  502. kv = read_gisrc()
  503. else:
  504. kv = {}
  505. kv['GISDBASE'] = gisdbase
  506. kv['LOCATION_NAME'] = location_name
  507. kv['MAPSET'] = mapset
  508. write_gisrc(kv)
  509. else:
  510. fatal(_("GISDBASE, LOCATION_NAME and MAPSET variables not set properly.\n"
  511. "Interactive startup needed."))
  512. def set_data():
  513. # User selects LOCATION and MAPSET if not set
  514. if not location:
  515. # Check for text interface
  516. if grass_gui == 'text':
  517. pass
  518. # Check for GUI
  519. elif grass_gui == 'wxpython':
  520. gui_startup()
  521. else:
  522. # Shouldn't need this but you never know
  523. fatal(_("Invalid user interface specified - <%s>.\n"
  524. "Use the --help option to see valid interface names.") % grass_gui)
  525. def gui_startup():
  526. if grass_gui == 'wxpython':
  527. thetest = call([os.getenv('GRASS_PYTHON'),
  528. gfile(wxpython_base, "gis_set.py")])
  529. if thetest == 0:
  530. pass
  531. elif thetest == 1:
  532. # The startup script printed an error message so wait
  533. # for user to read it
  534. message(_("Error in GUI startup. If necessary, please "
  535. "report this error to the GRASS developers.\n"
  536. "Switching to text mode now.\n\n"
  537. "Hit RETURN to continue..."))
  538. sys.stdin.readline()
  539. os.execlp(cmd_name, "-text")
  540. sys.exit(1)
  541. elif thetest == 2:
  542. # User wants to exit from GRASS
  543. message(_("Received EXIT message from GUI.\nGRASS is not started. Bye."))
  544. sys.exit(0)
  545. else:
  546. fatal(_("Invalid return code from GUI startup script.\n"
  547. "Please advise GRASS developers of this error."))
  548. def load_gisrc():
  549. global gisdbase, location_name, mapset, location
  550. kv = read_gisrc()
  551. gisdbase = kv.get('GISDBASE')
  552. location_name = kv.get('LOCATION_NAME')
  553. mapset = kv.get('MAPSET')
  554. if not gisdbase or not location_name or not mapset:
  555. fatal(_("Error reading data path information from g.gisenv.\n"
  556. "GISDBASE=%(gisbase)s\n"
  557. "LOCATION_NAME=%(location)s\n"
  558. "MAPSET=%(mapset)s\n\n"
  559. "Check the <%s(file)> file." % \
  560. { 'gisbase' : gisdbase, 'location' : location_name,
  561. 'mapset' : mapset, 'file' : gisrcrc }))
  562. location = os.path.join(gisdbase, location_name, mapset)
  563. def set_env_from_gisrc():
  564. kv = read_gisrc()
  565. ### addons
  566. if kv.get('ADDON_PATH'):
  567. addon_path = kv.get('ADDON_PATH')
  568. if os.getenv('GRASS_ADDON_PATH'):
  569. os.environ['GRASS_ADDON_PATH'] += os.pathsep + addon_path
  570. else:
  571. os.environ['GRASS_ADDON_PATH'] = addon_path
  572. ### language
  573. if kv.get('LANG'):
  574. os.environ['LANGUAGE'] = kv.get('LANG')
  575. def check_lock():
  576. global lockfile
  577. if not os.path.exists(location):
  578. fatal(_("Path '%s' doesn't exist") % location)
  579. # Check for concurrent use
  580. lockfile = os.path.join(location, ".gislock")
  581. ret = call([gfile("etc", "lock"),
  582. lockfile,
  583. "%d" % os.getpid()])
  584. if ret == 0:
  585. msg = None
  586. elif ret == 2:
  587. msg = _("%(user)s is currently running GRASS in selected mapset (file %(file)s found). "
  588. "Concurrent use not allowed." % \
  589. { 'user' : user, 'file' : lockfile })
  590. else:
  591. msg = _("Unable to properly access '%s'.\n"
  592. "Please notify system personel.") % lockfile
  593. if msg:
  594. if grass_gui == "wxpython":
  595. thetest = call([os.getenv('GRASS_PYTHON'), os.path.join(wxpython_base, "gis_set_error.py"), msg])
  596. else:
  597. global remove_lockfile
  598. remove_lockfile = False
  599. fatal(msg)
  600. def make_fontcap():
  601. fc = os.getenv('GRASS_FONT_CAP')
  602. if fc and not os.access(fc, os.R_OK):
  603. message(_("Building user fontcap..."))
  604. call(["g.mkfontcap"])
  605. def check_shell():
  606. global sh, shellname
  607. # cygwin has many problems with the shell setup
  608. # below, so i hardcoded everything here.
  609. if os.getenv('CYGWIN'):
  610. sh = "cygwin"
  611. shellname = "GNU Bash (Cygwin)"
  612. os.environ['SHELL'] = "/usr/bin/bash.exe"
  613. os.environ['OSTYPE'] = "cygwin"
  614. else:
  615. sh = os.path.basename(os.getenv('SHELL'))
  616. if sh == "ksh":
  617. shellname = "Korn Shell"
  618. elif sh == "csh":
  619. shellname = "C Shell"
  620. elif sh == "tcsh":
  621. shellname = "TC Shell"
  622. elif sh == "bash":
  623. shellname = "Bash Shell"
  624. elif sh == "sh":
  625. shellname = "Bourne Shell"
  626. else:
  627. shellname = "shell"
  628. # check for SHELL
  629. if not os.getenv('SHELL'):
  630. fatal(_("The SHELL variable is not set"))
  631. def check_batch_job():
  632. global batch_job
  633. # hack to process batch jobs:
  634. batch_job = os.getenv('GRASS_BATCH_JOB')
  635. if batch_job:
  636. # defined, but ...
  637. if not os.access(batch_job, os.F_OK):
  638. # wrong file
  639. fatal(_("Job file '%s' has been defined in "
  640. "the 'GRASS_BATCH_JOB' variable but not found. Exiting.\n\n"
  641. "Use 'unset GRASS_BATCH_JOB' to disable batch job processing.") % batch_job)
  642. elif not os.access(batch_job, os.X_OK):
  643. # right file, but ...
  644. fatal(_("Change file permission to 'executable' for '%s'") % batch_job)
  645. else:
  646. message(_("Executing '%s' ...") % batch_job)
  647. grass_gui = "text"
  648. shell = batch_job
  649. bj = Popen(shell, shell=True)
  650. bj.wait()
  651. message(_("Execution of '%s' finished.") % batch_job)
  652. def start_gui():
  653. # Start the chosen GUI but ignore text
  654. if grass_debug:
  655. message(_("GRASS GUI should be <%s>") % grass_gui)
  656. # Check for gui interface
  657. if grass_gui == "wxpython":
  658. Popen([os.getenv('GRASS_PYTHON'),
  659. gfile(wxpython_base, "wxgui.py")])
  660. def clear_screen():
  661. if windows:
  662. pass
  663. # TODO: uncomment when PDCurses works.
  664. # cls
  665. else:
  666. if not os.getenv('GRASS_BATCH_JOB') and not grass_debug:
  667. call(["tput", "clear"])
  668. def show_banner():
  669. sys.stderr.write(r"""
  670. __________ ___ __________ _______________
  671. / ____/ __ \/ | / ___/ ___/ / ____/ _/ ___/
  672. / / __/ /_/ / /| | \__ \\_ \ / / __ / / \__ \
  673. / /_/ / _, _/ ___ |___/ /__/ / / /_/ // / ___/ /
  674. \____/_/ |_/_/ |_/____/____/ \____/___//____/
  675. """)
  676. def say_hello():
  677. sys.stderr.write(_("Welcome to GRASS %s") % grass_version)
  678. def show_info():
  679. sys.stderr.write(
  680. r"""
  681. %-41shttp://grass.osgeo.org
  682. %-41s%s (%s)
  683. %-41sg.manual -i
  684. %-41sg.version -c
  685. """ % (_("GRASS homepage:"),
  686. _("This version running through:"),
  687. shellname, os.getenv('SHELL'),
  688. _("Help is available with the command:"),
  689. _("See the licence terms with:")))
  690. if grass_gui == 'wxpython':
  691. message("%-41sg.gui wxpython" % _("If required, restart the GUI with:"))
  692. else:
  693. message("%-41sg.gui %s" % (_("Start the GUI with:"), default_gui))
  694. message("%-41sexit" % _("When ready to quit enter:"))
  695. message("")
  696. def csh_startup():
  697. global exit_val
  698. userhome = os.getenv('HOME') # save original home
  699. home = location
  700. os.environ['HOME'] = home
  701. cshrc = os.path.join(home, ".cshrc")
  702. tcshrc = os.path.join(home, ".tcshrc")
  703. try_remove(cshrc)
  704. try_remove(tcshrc)
  705. f = open(cshrc, 'w')
  706. f.write("set home = %s" % userhome)
  707. f.write("set history = 3000 savehist = 3000 noclobber ignoreeof")
  708. f.write("set histfile = %s" % os.path.join(os.getenv('HOME'), ".history"))
  709. f.write("set prompt = '\\")
  710. f.write("Mapset <%s> in Location <%s> \\" % (mapset, location_name))
  711. f.write("GRASS %s > '" % grass_version)
  712. f.write("set BOGUS=``;unset BOGUS")
  713. path = os.path.join(userhome, ".grass.cshrc")
  714. if os.access(path, os.R_OK):
  715. f.write(readfile(path))
  716. mail_re = re.compile(r"^ *set *mail *= *")
  717. for filename in [".cshrc", ".tcshrc", ".login"]:
  718. path = os.path.join(userhome, filename)
  719. if os.access(path, os.R_OK):
  720. s = readfile(path)
  721. lines = s.splitlines()
  722. for l in lines:
  723. if mail_re.match(l):
  724. f.write(l)
  725. path = os.getenv('PATH').split(':')
  726. f.write("set path = ( %s ) " % ' '.join(path))
  727. f.close()
  728. writefile(tcshrc, readfile(cshrc))
  729. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  730. os.environ['HOME'] = userhome
  731. def bash_startup():
  732. global exit_val
  733. # save command history in mapset dir and remember more
  734. os.environ['HISTFILE'] = os.path.join(location, ".bash_history")
  735. if not os.getenv('HISTSIZE') and not os.getenv('HISTFILESIZE'):
  736. os.environ['HISTSIZE'] = "3000"
  737. # instead of changing $HOME, start bash with: --rcfile "$LOCATION/.bashrc" ?
  738. # if so, must care be taken to explicity call .grass.bashrc et al for
  739. # non-interactive bash batch jobs?
  740. userhome = os.getenv('HOME') # save original home
  741. home = location # save .bashrc in $LOCATION
  742. os.environ['HOME'] = home
  743. bashrc = os.path.join(home, ".bashrc")
  744. try_remove(bashrc)
  745. f = open(bashrc, 'w')
  746. f.write("test -r ~/.alias && . ~/.alias\n")
  747. f.write("PS1='GRASS %s (%s):\w > '\n" % (grass_version, location_name))
  748. f.write("PROMPT_COMMAND=\"'%s'\"\n" % os.path.join(gisbase, 'etc', 'prompt.py'))
  749. path = os.path.join(userhome, ".grass.bashrc")
  750. if os.access(path, os.R_OK):
  751. f.write(readfile(path) + '\n')
  752. f.write("export PATH=\"%s\"\n" % os.getenv('PATH'))
  753. f.write("export HOME=\"%s\"\n" % userhome) # restore user home path
  754. f.close()
  755. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  756. os.environ['HOME'] = userhome
  757. def default_startup():
  758. global exit_val
  759. if windows:
  760. os.environ['PS1'] = "GRASS %s> " % (grass_version)
  761. # "$ETC/run" doesn't work at all???
  762. exit_val = subprocess.call([os.getenv('SHELL')])
  763. cleanup_dir(os.path.join(location, ".tmp")) # remove GUI session files from .tmp
  764. else:
  765. os.environ['PS1'] = "GRASS %s (%s):\w > " % (grass_version, location_name)
  766. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  767. if exit_val != 0:
  768. fatal(_("Failed to start shell '%s'") % os.getenv('SHELL'))
  769. def done_message():
  770. if batch_job and os.access(batch_job, os.X_OK):
  771. message(_("Batch job '%s' (defined in GRASS_BATCH_JOB variable) was executed.") % batch_job)
  772. message(_("Goodbye from GRASS GIS"))
  773. sys.exit(exit_val)
  774. else:
  775. message(_("Done."))
  776. message("")
  777. message(_("Goodbye from GRASS GIS"))
  778. message("")
  779. def clean_temp():
  780. message(_("Cleaning up temporary files..."))
  781. nul = open(os.devnull, 'w')
  782. call([gfile("etc", "clean_temp")], stdout = nul, stderr = nul)
  783. nul.close()
  784. def grep(string,list):
  785. expr = re.compile(string)
  786. return [elem for elem in list if expr.match(elem)]
  787. def print_params():
  788. plat = gfile(gisbase, 'include', 'Make', 'Platform.make')
  789. fileplat = open(plat)
  790. linesplat = fileplat.readlines()
  791. fileplat.close()
  792. params = sys.argv[2:]
  793. if not params:
  794. params = ['arch', 'build', 'compiler', 'path', 'revision']
  795. for arg in params:
  796. if arg == 'path':
  797. sys.stdout.write("%s\n" % gisbase)
  798. elif arg == 'arch':
  799. val = grep('ARCH',linesplat)
  800. sys.stdout.write("%s\n" % val[0].split('=')[1].strip())
  801. elif arg == 'build':
  802. build = os.path.join(gisbase,'include','grass','confparms.h')
  803. filebuild = open(build)
  804. val = filebuild.readline()
  805. filebuild.close()
  806. sys.stdout.write("%s\n" % val.strip().strip('"').strip())
  807. elif arg == 'compiler':
  808. val = grep('CC',linesplat)
  809. sys.stdout.write("%s\n" % val[0].split('=')[1].strip())
  810. elif arg == 'revision':
  811. rev = os.path.join(gisbase,'include','grass','gis.h')
  812. filerev = open(rev)
  813. linesrev = filerev.readlines()
  814. val = grep('#define GIS_H_VERSION', linesrev)
  815. filerev.close()
  816. sys.stdout.write("%s\n" % val[0].split(':')[1].rstrip('$"\n').strip())
  817. else:
  818. message(_("Parameter <%s> not supported") % arg)
  819. def get_username():
  820. global user
  821. if windows:
  822. user = os.getenv('USERNAME')
  823. if not user:
  824. user = "user_name"
  825. else:
  826. user = os.getenv('USER')
  827. if not user:
  828. user = os.getenv('LOGNAME')
  829. if not user:
  830. try:
  831. p = Popen(['whoami'], stdout = subprocess.PIPE)
  832. s = p.stdout.read()
  833. p.wait()
  834. user = s.strip()
  835. except:
  836. pass
  837. if not user:
  838. user = "user_%d" % os.getuid()
  839. def parse_cmdline():
  840. global args, grass_gui, create_new
  841. args = []
  842. for i in sys.argv[1:]:
  843. # Check if the user asked for the version
  844. if i in ["-v", "--version"]:
  845. message('\n' + readfile(gfile("etc", "license")))
  846. sys.exit()
  847. # Check if the user asked for help
  848. elif i in ["help", "-h", "-help", "--help"]:
  849. help_message()
  850. sys.exit()
  851. # Check if the -text flag was given
  852. elif i in ["-text", "--text"]:
  853. grass_gui = 'text'
  854. # Check if the -gui flag was given
  855. elif i in ["-gui", "--gui"]:
  856. grass_gui = default_gui
  857. # Check if the -wxpython flag was given
  858. elif i in ["-wxpython", "-wx", "--wxpython", "--wx"]:
  859. grass_gui = 'wxpython'
  860. # Check if the user wants to create a new mapset
  861. elif i == "-c":
  862. create_new = True
  863. elif i == "--config":
  864. print_params()
  865. sys.exit()
  866. else:
  867. args.append(i)
  868. ### MAIN script starts here
  869. # Get the system name
  870. windows = sys.platform == 'win32'
  871. cygwin = "cygwin" in sys.platform
  872. macosx = "darwin" in sys.platform
  873. # Set GISBASE
  874. os.environ['GISBASE'] = gisbase
  875. # set HOME
  876. if windows and not os.getenv('HOME'):
  877. os.environ['HOME'] = os.path.join(os.getenv('HOMEDRIVE'), os.getenv('HOMEPATH'))
  878. # set SHELL
  879. if windows:
  880. if os.getenv('GRASS_SH'):
  881. os.environ['SHELL'] = os.getenv('GRASS_SH')
  882. if not os.getenv('SHELL'):
  883. os.environ['SHELL'] = os.getenv('COMSPEC', 'cmd.exe')
  884. atexit.register(cleanup)
  885. # Set default GUI
  886. default_gui = "wxpython"
  887. # the following is only meant to be an internal variable for debugging this script.
  888. # use 'g.gisenv set="DEBUG=[0-5]"' to turn GRASS debug mode on properly.
  889. grass_debug = os.getenv('GRASS_DEBUG')
  890. # Set GRASS version number for R interface etc (must be an env_var for MS-Windows)
  891. os.environ['GRASS_VERSION'] = grass_version
  892. # Set the GIS_LOCK variable to current process id
  893. gis_lock = str(os.getpid())
  894. os.environ['GIS_LOCK'] = gis_lock
  895. # Set the global grassrc file
  896. batch_job = os.getenv('GRASS_BATCH_JOB')
  897. if batch_job:
  898. gisrcrc = os.path.join(grass_config_dir, "rc.%s" % platform.node())
  899. if not os.access(gisrcrc, os.R_OK):
  900. gisrcrc = os.path.join(grass_config_dir, "rc")
  901. else:
  902. gisrcrc = os.path.join(grass_config_dir, "rc")
  903. # Set the username and working directory
  904. get_username()
  905. # Parse the command-line options
  906. parse_cmdline()
  907. # Create the temporary directory and session grassrc file
  908. create_tmp()
  909. # Create the session grassrc file
  910. create_gisrc()
  911. # Ensure GUI is set
  912. read_gui()
  913. # Get environmental variables from gisenv variables
  914. set_env_from_gisrc()
  915. # Get Locale name
  916. get_locale()
  917. # Set PATH, PYTHONPATH
  918. set_paths()
  919. # Set LD_LIBRARY_PATH (etc) to find GRASS shared libraries
  920. path_prepend(gfile("lib"), ld_library_path_var)
  921. # Set GRASS_PAGER, GRASS_WISH, GRASS_PYTHON, GRASS_GNUPLOT, GRASS_PROJSHARE
  922. set_defaults()
  923. # Set GRASS_HTML_BROWSER
  924. set_browser()
  925. #predefine monitor size for certain architectures
  926. if os.getenv('HOSTTYPE') == 'arm':
  927. # small monitor on ARM (iPAQ, zaurus... etc)
  928. os.environ['GRASS_HEIGHT'] = "320"
  929. os.environ['GRASS_WIDTH'] = "240"
  930. # First time user - GISRC is defined in the GRASS script
  931. if not os.access(gisrc, os.F_OK):
  932. if grass_gui == 'text' and len(args) == 0:
  933. fatal(_("Unable to start GRASS. You can:\n"
  934. " - Launch GRASS with '-gui' switch (`grass70 -gui`)\n"
  935. " - Create manually GISRC file (%s)\n"
  936. " - Launch GRASS with path to "
  937. "the location/mapset as an argument (`grass70 /path/to/location/mapset`)") % gisrcrc)
  938. grass_intro()
  939. else:
  940. clean_temp()
  941. message(_("Starting GRASS GIS..."))
  942. # Check that the GUI works
  943. check_gui()
  944. # Parsing argument to get LOCATION
  945. if not args:
  946. # Try interactive startup
  947. location = None
  948. else:
  949. if create_new:
  950. if len(args) > 1:
  951. non_interactive(args[1], args[0])
  952. else:
  953. non_interactive(args[0])
  954. else:
  955. non_interactive(args[0])
  956. # User selects LOCATION and MAPSET if not set
  957. set_data()
  958. # Set GISDBASE, LOCATION_NAME, MAPSET, LOCATION from $GISRC
  959. load_gisrc()
  960. # Check .gislock file
  961. check_lock()
  962. # build user fontcap if specified but not present
  963. make_fontcap()
  964. # predefine default driver if DB connection not defined
  965. # is this really needed?? Modules should call this when/if required.
  966. if not os.access(os.path.join(location, "VAR"), os.F_OK):
  967. call(['db.connect', '-c', '--quiet'])
  968. check_shell()
  969. check_batch_job()
  970. if not batch_job:
  971. start_gui()
  972. clear_screen()
  973. # Display the version and license info
  974. if batch_job:
  975. say_hello()
  976. grass_gui = 'text'
  977. clear_screen()
  978. clean_temp()
  979. try_remove(lockfile)
  980. sys.exit(0)
  981. else:
  982. show_banner()
  983. say_hello()
  984. show_info()
  985. if grass_gui == "wxpython":
  986. message(_("Launching <%s> GUI in the background, please wait...") % grass_gui)
  987. if sh in ['csh', 'tcsh']:
  988. csh_startup()
  989. elif sh in ['bash', 'msh', 'cygwin']:
  990. bash_startup()
  991. else:
  992. default_startup()
  993. clear_screen()
  994. clean_env()
  995. clean_temp()
  996. try_remove(lockfile)
  997. # Save GISRC
  998. s = readfile(gisrc)
  999. if not os.path.exists(grass_config_dir):
  1000. os.mkdir(grass_config_dir)
  1001. writefile(gisrcrc, s)
  1002. cleanup()
  1003. # After this point no more grass modules may be called
  1004. done_message()