grass.py 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171
  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. # Add .py (Python) to list of executable extensions to search for in MS-Windows PATH
  296. if windows:
  297. path_append('.PY', 'PATHEXT')
  298. def find_exe(pgm):
  299. for dir in os.getenv('PATH').split(os.pathsep):
  300. path = os.path.join(dir, pgm)
  301. if os.access(path, os.X_OK):
  302. return path
  303. return None
  304. def set_defaults():
  305. # GRASS_PAGER
  306. if not os.getenv('GRASS_PAGER'):
  307. if find_exe("more"):
  308. pager = "more"
  309. elif find_exe("less"):
  310. pager = "less"
  311. elif windows:
  312. pager = "more"
  313. else:
  314. pager = "cat"
  315. os.environ['GRASS_PAGER'] = pager
  316. # GRASS_WISH
  317. if not os.getenv('GRASS_WISH'):
  318. os.environ['GRASS_WISH'] = "wish"
  319. # GRASS_PYTHON
  320. if not os.getenv('GRASS_PYTHON'):
  321. if windows:
  322. os.environ['GRASS_PYTHON'] = "python.exe"
  323. else:
  324. os.environ['GRASS_PYTHON'] = "python"
  325. # GRASS_GNUPLOT
  326. if not os.getenv('GRASS_GNUPLOT'):
  327. os.environ['GRASS_GNUPLOT'] = "gnuplot -persist"
  328. # GRASS_PROJSHARE
  329. if not os.getenv('GRASS_PROJSHARE'):
  330. os.environ['GRASS_PROJSHARE'] = config_projshare
  331. def set_browser():
  332. # GRASS_HTML_BROWSER
  333. browser = os.getenv('GRASS_HTML_BROWSER')
  334. if not browser:
  335. if macosx:
  336. # OSX doesn't execute browsers from the shell PATH - route thru a script
  337. browser = gfile('etc', "html_browser_mac.sh")
  338. os.environ['GRASS_HTML_BROWSER_MACOSX'] = "-b com.apple.helpviewer"
  339. if windows or cygwin:
  340. # MinGW startup moved to into init.bat
  341. browser = "explorer"
  342. else:
  343. # the usual suspects
  344. browsers = [ "xdg-open", "htmlview", "konqueror", "mozilla", "mozilla-firefox",
  345. "firefox", "iceweasel", "opera", "netscape", "dillo", "lynx", "links", "w3c" ]
  346. for b in browsers:
  347. if find_exe(b):
  348. browser = b
  349. break
  350. elif macosx:
  351. # OSX doesn't execute browsers from the shell PATH - route thru a script
  352. os.environ['GRASS_HTML_BROWSER_MACOSX'] = "-b %s" % browser
  353. browser = gfile('etc', "html_browser_mac.sh")
  354. if not browser:
  355. warning(_("Searched for a web browser, but none found"))
  356. # even so we set konqueror to make lib/gis/parser.c happy:
  357. browser = "konqueror"
  358. os.environ['GRASS_HTML_BROWSER'] = browser
  359. def grass_intro():
  360. if locale:
  361. path = gfile("locale", locale, "etc", "grass_intro")
  362. if not os.access(path, os.R_OK):
  363. path = gfile("etc", "grass_intro")
  364. else:
  365. path = gfile("etc", "grass_intro")
  366. f = open(path, 'r')
  367. for line in f:
  368. sys.stderr.write(line)
  369. f.close()
  370. sys.stderr.write("\n")
  371. sys.stderr.write(_("Hit RETURN to continue"))
  372. sys.stdin.readline()
  373. #for convenience, define pwd as GISDBASE:
  374. s = r"""GISDBASE: %s
  375. LOCATION_NAME: <UNKNOWN>
  376. MAPSET: <UNKNOWN>
  377. """ % os.getcwd()
  378. writefile(gisrc, s)
  379. def check_gui():
  380. global grass_gui, wxpython_base
  381. # Check if we are running X windows by checking the DISPLAY variable
  382. if os.getenv('DISPLAY') or windows:
  383. # Check if python is working properly
  384. if grass_gui == 'wxpython':
  385. nul = open(os.devnull, 'w')
  386. p = Popen([os.environ['GRASS_PYTHON']],
  387. stdin = subprocess.PIPE,
  388. stdout = nul, stderr = nul)
  389. nul.close()
  390. p.stdin.write("variable=True")
  391. p.stdin.close()
  392. p.wait()
  393. if p.returncode == 0:
  394. # Set the wxpython base directory
  395. wxpython_base = gfile("etc", "gui", "wxpython")
  396. else:
  397. # Python was not found - switch to text interface mode
  398. warning(_("The python command does not work as expected!\n"
  399. "Please check your GRASS_PYTHON environment variable.\n"
  400. "Use the -help option for details.\n"
  401. "Switching to text based interface mode.\n\n"
  402. "Hit RETURN to continue.\n"))
  403. sys.stdin.readline()
  404. grass_gui = 'text'
  405. else:
  406. # Display a message if a graphical interface was expected
  407. if grass_gui != 'text':
  408. # Set the interface mode to text
  409. warning(_("It appears that the X Windows system is not active.\n"
  410. "A graphical based user interface is not supported.\n"
  411. "Switching to text based interface mode.\n\n"
  412. "Hit RETURN to continue"""))
  413. sys.stdin.readline()
  414. grass_gui = 'text'
  415. # Save the user interface variable in the grassrc file - choose a temporary
  416. # file name that should not match another file
  417. if os.access(gisrc, os.F_OK):
  418. kv = read_gisrc()
  419. kv['GUI'] = grass_gui
  420. write_gisrc(kv)
  421. def non_interactive(arg, geofile = None):
  422. global gisdbase, location_name, mapset, location
  423. # Try non-interactive startup
  424. l = None
  425. if arg == '-':
  426. if location:
  427. l = location
  428. else:
  429. l = arg
  430. if l:
  431. if l == '.':
  432. l = os.getcwd()
  433. elif not os.path.isabs(l):
  434. l = os.path.abspath(l)
  435. l, mapset = os.path.split(l)
  436. if not mapset:
  437. l, mapset = os.path.split(l)
  438. l, location_name = os.path.split(l)
  439. gisdbase = l
  440. if gisdbase and location_name and mapset:
  441. location = os.path.join(gisdbase, location_name, mapset)
  442. if not os.access(os.path.join(location, "WIND"), os.R_OK):
  443. if location_name == "PERMANENT":
  444. fatal(_("<%s> is not a valid GRASS location") % location)
  445. else:
  446. # the user wants to create mapset on the fly
  447. if create_new:
  448. if not os.access(os.path.join(os.path.join(gisdbase, location_name,
  449. "PERMANENT", "DEFAULT_WIND")), os.F_OK):
  450. # create new location
  451. gisdbase = os.path.join(gisdbase, location_name)
  452. location_name = mapset
  453. mapset = "PERMANENT"
  454. if os.access(os.path.join(os.path.join(gisdbase, location_name,
  455. "PERMANENT", "DEFAULT_WIND")), os.F_OK):
  456. fatal(_("Failed to create new location. The location <%s> already exists." % location_name))
  457. sys.path.append(gfile('etc', 'python'))
  458. from grass.script import core as grass
  459. try:
  460. if geofile and geofile.find('EPSG:') > -1:
  461. epsg = geofile.split(':', 1)[1]
  462. grass.create_location(gisdbase, location_name, epsg = epsg)
  463. else:
  464. grass.create_location(gisdbase, location_name, filename = geofile)
  465. except grass.ScriptError, e:
  466. fatal(e.value.strip('"').strip("'").replace('\\n', os.linesep))
  467. else:
  468. # create new mapset
  469. os.mkdir(location)
  470. # copy PERMANENT/DEFAULT_WIND to <mapset>/WIND
  471. s = readfile(os.path.join(gisdbase, location_name, "PERMANENT", "DEFAULT_WIND"))
  472. writefile(os.path.join(location, "WIND"), s)
  473. message(_("Missing WIND file fixed"))
  474. else:
  475. fatal(_("<%s> is not a valid GRASS location") % location)
  476. if os.access(gisrc, os.R_OK):
  477. kv = read_gisrc()
  478. else:
  479. kv = {}
  480. kv['GISDBASE'] = gisdbase
  481. kv['LOCATION_NAME'] = location_name
  482. kv['MAPSET'] = mapset
  483. write_gisrc(kv)
  484. else:
  485. fatal(_("GISDBASE, LOCATION_NAME and MAPSET variables not set properly.\n"
  486. "Interactive startup needed."))
  487. def set_data():
  488. # User selects LOCATION and MAPSET if not set
  489. if not location:
  490. # Check for text interface
  491. if grass_gui == 'text':
  492. pass
  493. # Check for GUI
  494. elif grass_gui == 'wxpython':
  495. gui_startup()
  496. else:
  497. # Shouldn't need this but you never know
  498. fatal(_("Invalid user interface specified - <%s>.\n"
  499. "Use the --help option to see valid interface names.") % grass_gui)
  500. def gui_startup():
  501. if grass_gui == 'wxpython':
  502. thetest = call([os.getenv('GRASS_PYTHON'),
  503. gfile(wxpython_base, "gis_set.py")])
  504. if thetest == 0:
  505. pass
  506. elif thetest == 1:
  507. # The startup script printed an error message so wait
  508. # for user to read it
  509. message(_("Error in GUI startup. If necessary, please "
  510. "report this error to the GRASS developers.\n"
  511. "Switching to text mode now.\n\n"
  512. "Hit RETURN to continue..."))
  513. sys.stdin.readline()
  514. os.execlp(cmd_name, "-text")
  515. sys.exit(1)
  516. elif thetest == 2:
  517. # User wants to exit from GRASS
  518. message(_("Received EXIT message from GUI.\nGRASS is not started. Bye."))
  519. sys.exit(0)
  520. else:
  521. fatal(_("Invalid return code from GUI startup script.\n"
  522. "Please advise GRASS developers of this error."))
  523. def load_gisrc():
  524. global gisdbase, location_name, mapset, location
  525. kv = read_gisrc()
  526. gisdbase = kv.get('GISDBASE')
  527. location_name = kv.get('LOCATION_NAME')
  528. mapset = kv.get('MAPSET')
  529. if not gisdbase or not location_name or not mapset:
  530. fatal(_("Error reading data path information from g.gisenv.\n"
  531. "GISDBASE=%(gisbase)s\n"
  532. "LOCATION_NAME=%(location)s\n"
  533. "MAPSET=%(mapset)s\n\n"
  534. "Check the <%s(file)> file." % \
  535. { 'gisbase' : gisdbase, 'location' : location_name,
  536. 'mapset' : mapset, 'file' : gisrcrc }))
  537. location = os.path.join(gisdbase, location_name, mapset)
  538. def set_env_from_gisrc():
  539. kv = read_gisrc()
  540. ### addons
  541. if kv.get('ADDON_PATH'):
  542. addon_path = kv.get('ADDON_PATH')
  543. if os.getenv('GRASS_ADDON_PATH'):
  544. os.environ['GRASS_ADDON_PATH'] += os.pathsep + addon_path
  545. else:
  546. os.environ['GRASS_ADDON_PATH'] = addon_path
  547. ### language
  548. if kv.get('LANG'):
  549. os.environ['LANGUAGE'] = kv.get('LANG')
  550. def check_lock():
  551. global lockfile
  552. if not os.path.exists(location):
  553. fatal(_("Path '%s' doesn't exist") % location)
  554. # Check for concurrent use
  555. lockfile = os.path.join(location, ".gislock")
  556. ret = call([gfile("etc", "lock"),
  557. lockfile,
  558. "%d" % os.getpid()])
  559. if ret == 0:
  560. msg = None
  561. elif ret == 2:
  562. msg = _("%(user)s is currently running GRASS in selected mapset (file %(file)s found). "
  563. "Concurrent use not allowed." % \
  564. { 'user' : user, 'file' : lockfile })
  565. else:
  566. msg = _("Unable to properly access '%s'.\n"
  567. "Please notify system personel.") % lockfile
  568. if msg:
  569. if grass_gui == "wxpython":
  570. thetest = call([os.getenv('GRASS_PYTHON'), os.path.join(wxpython_base, "gis_set_error.py"), msg])
  571. else:
  572. global remove_lockfile
  573. remove_lockfile = False
  574. fatal(msg)
  575. def make_fontcap():
  576. fc = os.getenv('GRASS_FONT_CAP')
  577. if fc and not os.access(fc, os.R_OK):
  578. message(_("Building user fontcap..."))
  579. call(["g.mkfontcap"])
  580. def check_shell():
  581. global sh, shellname
  582. # cygwin has many problems with the shell setup
  583. # below, so i hardcoded everything here.
  584. if os.getenv('CYGWIN'):
  585. sh = "cygwin"
  586. shellname = "GNU Bash (Cygwin)"
  587. os.environ['SHELL'] = "/usr/bin/bash.exe"
  588. os.environ['OSTYPE'] = "cygwin"
  589. else:
  590. sh = os.path.basename(os.getenv('SHELL'))
  591. if sh == "ksh":
  592. shellname = "Korn Shell"
  593. elif sh == "csh":
  594. shellname = "C Shell"
  595. elif sh == "tcsh":
  596. shellname = "TC Shell"
  597. elif sh == "bash":
  598. shellname = "Bash Shell"
  599. elif sh == "sh":
  600. shellname = "Bourne Shell"
  601. else:
  602. shellname = "shell"
  603. # check for SHELL
  604. if not os.getenv('SHELL'):
  605. fatal(_("The SHELL variable is not set"))
  606. def check_batch_job():
  607. global batch_job
  608. # hack to process batch jobs:
  609. batch_job = os.getenv('GRASS_BATCH_JOB')
  610. if batch_job:
  611. # defined, but ...
  612. if not os.access(batch_job, os.F_OK):
  613. # wrong file
  614. fatal(_("Job file '%s' has been defined in "
  615. "the 'GRASS_BATCH_JOB' variable but not found. Exiting.\n\n"
  616. "Use 'unset GRASS_BATCH_JOB' to disable batch job processing.") % batch_job)
  617. elif not os.access(batch_job, os.X_OK):
  618. # right file, but ...
  619. fatal(_("Change file permission to 'executable' for '%s'") % batch_job)
  620. else:
  621. message(_("Executing '%s' ...") % batch_job)
  622. grass_gui = "text"
  623. shell = batch_job
  624. bj = Popen(shell, shell=True)
  625. bj.wait()
  626. message(_("Execution of '%s' finished.") % batch_job)
  627. def start_gui():
  628. # Start the chosen GUI but ignore text
  629. if grass_debug:
  630. message(_("GRASS GUI should be <%s>") % grass_gui)
  631. # Check for gui interface
  632. if grass_gui == "wxpython":
  633. Popen([os.getenv('GRASS_PYTHON'),
  634. gfile(wxpython_base, "wxgui.py")])
  635. def clear_screen():
  636. if windows:
  637. pass
  638. # TODO: uncomment when PDCurses works.
  639. # cls
  640. else:
  641. if not os.getenv('GRASS_BATCH_JOB') and not grass_debug:
  642. call(["tput", "clear"])
  643. def show_banner():
  644. sys.stderr.write(r"""
  645. __________ ___ __________ _______________
  646. / ____/ __ \/ | / ___/ ___/ / ____/ _/ ___/
  647. / / __/ /_/ / /| | \__ \\_ \ / / __ / / \__ \
  648. / /_/ / _, _/ ___ |___/ /__/ / / /_/ // / ___/ /
  649. \____/_/ |_/_/ |_/____/____/ \____/___//____/
  650. """)
  651. def say_hello():
  652. if locale:
  653. path = gfile("locale", locale, "etc", "welcome")
  654. if not os.access(path, os.R_OK):
  655. path = gfile("etc", "welcome")
  656. else:
  657. path = gfile("etc", "welcome")
  658. s = readfile(path)
  659. sys.stderr.write(s)
  660. def show_info():
  661. sys.stderr.write(
  662. r"""
  663. %-41shttp://grass.osgeo.org
  664. %-41s%s (%s)
  665. %-41sg.manual -i
  666. %-41sg.version -c
  667. """ % (_("GRASS homepage:"),
  668. _("This version running through:"),
  669. shellname, os.getenv('SHELL'),
  670. _("Help is available with the command:"),
  671. _("See the licence terms with:")))
  672. if grass_gui == 'wxpython':
  673. message("%-41sg.gui wxpython" % _("If required, restart the GUI with:"))
  674. else:
  675. message("%-41sg.gui %s" % (_("Start the GUI with:"), default_gui))
  676. message("%-41sexit" % _("When ready to quit enter:"))
  677. message("")
  678. def csh_startup():
  679. global exit_val
  680. userhome = os.getenv('HOME') # save original home
  681. home = location
  682. os.environ['HOME'] = home
  683. cshrc = os.path.join(home, ".cshrc")
  684. tcshrc = os.path.join(home, ".tcshrc")
  685. try_remove(cshrc)
  686. try_remove(tcshrc)
  687. f = open(cshrc, 'w')
  688. f.write("set home = %s" % userhome)
  689. f.write("set history = 3000 savehist = 3000 noclobber ignoreeof")
  690. f.write("set histfile = %s" % os.path.join(os.getenv('HOME'), ".history"))
  691. f.write("set prompt = '\\")
  692. f.write("Mapset <%s> in Location <%s> \\" % (mapset, location_name))
  693. f.write("GRASS %s > '" % grass_version)
  694. f.write("set BOGUS=``;unset BOGUS")
  695. path = os.path.join(userhome, ".grass.cshrc")
  696. if os.access(path, os.R_OK):
  697. f.write(readfile(path))
  698. mail_re = re.compile(r"^ *set *mail *= *")
  699. for filename in [".cshrc", ".tcshrc", ".login"]:
  700. path = os.path.join(userhome, filename)
  701. if os.access(path, os.R_OK):
  702. s = readfile(path)
  703. lines = s.splitlines()
  704. for l in lines:
  705. if mail_re.match(l):
  706. f.write(l)
  707. path = os.getenv('PATH').split(':')
  708. f.write("set path = ( %s ) " % ' '.join(path))
  709. f.close()
  710. writefile(tcshrc, readfile(cshrc))
  711. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  712. os.environ['HOME'] = userhome
  713. def bash_startup():
  714. global exit_val
  715. # save command history in mapset dir and remember more
  716. os.environ['HISTFILE'] = os.path.join(location, ".bash_history")
  717. if not os.getenv('HISTSIZE') and not os.getenv('HISTFILESIZE'):
  718. os.environ['HISTSIZE'] = "3000"
  719. # instead of changing $HOME, start bash with: --rcfile "$LOCATION/.bashrc" ?
  720. # if so, must care be taken to explicity call .grass.bashrc et al for
  721. # non-interactive bash batch jobs?
  722. userhome = os.getenv('HOME') # save original home
  723. home = location # save .bashrc in $LOCATION
  724. os.environ['HOME'] = home
  725. bashrc = os.path.join(home, ".bashrc")
  726. try_remove(bashrc)
  727. f = open(bashrc, 'w')
  728. f.write("test -r ~/.alias && . ~/.alias\n")
  729. f.write("PS1='GRASS %s (%s):\w > '\n" % (grass_version, location_name))
  730. f.write("PROMPT_COMMAND=\"'%s'\"\n" % os.path.join(gisbase, 'etc', 'prompt.py'))
  731. path = os.path.join(userhome, ".grass.bashrc")
  732. if os.access(path, os.R_OK):
  733. f.write(readfile(path) + '\n')
  734. f.write("export PATH=\"%s\"\n" % os.getenv('PATH'))
  735. f.write("export HOME=\"%s\"\n" % userhome) # restore user home path
  736. for env, value in os.environ.iteritems():
  737. if env.find('GRASS_') < 0:
  738. continue
  739. f.write("export %s=\"%s\"\n" % (env, value))
  740. f.close()
  741. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  742. os.environ['HOME'] = userhome
  743. def default_startup():
  744. global exit_val
  745. if windows:
  746. os.environ['PS1'] = "GRASS %s> " % (grass_version)
  747. # "$ETC/run" doesn't work at all???
  748. exit_val = subprocess.call([os.getenv('SHELL')])
  749. cleanup_dir(os.path.join(location, ".tmp")) # remove GUI session files from .tmp
  750. else:
  751. os.environ['PS1'] = "GRASS %s (%s):\w > " % (grass_version, location_name)
  752. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  753. if exit_val != 0:
  754. fatal(_("Failed to start shell '%s'") % os.getenv('SHELL'))
  755. def done_message():
  756. if batch_job and os.access(batch_job, os.X_OK):
  757. message(_("Batch job '%s' (defined in GRASS_BATCH_JOB variable) was executed.") % batch_job)
  758. message(_("Goodbye from GRASS GIS"))
  759. sys.exit(exit_val)
  760. else:
  761. message(_("Done."))
  762. message("")
  763. message(_("Goodbye from GRASS GIS"))
  764. message("")
  765. def clean_temp():
  766. message(_("Cleaning up temporary files..."))
  767. nul = open(os.devnull, 'w')
  768. call([gfile("etc", "clean_temp")], stdout = nul, stderr = nul)
  769. nul.close()
  770. def grep(string,list):
  771. expr = re.compile(string)
  772. return [elem for elem in list if expr.match(elem)]
  773. def print_params():
  774. plat = gfile(gisbase, 'include', 'Make', 'Platform.make')
  775. fileplat = open(plat)
  776. linesplat = fileplat.readlines()
  777. fileplat.close()
  778. params = sys.argv[2:]
  779. if not params:
  780. params = ['arch', 'build', 'compiler', 'path', 'revision']
  781. for arg in params:
  782. if arg == 'path':
  783. sys.stdout.write("%s\n" % gisbase)
  784. elif arg == 'arch':
  785. val = grep('ARCH',linesplat)
  786. sys.stdout.write("%s\n" % val[0].split('=')[1].strip())
  787. elif arg == 'build':
  788. build = os.path.join(gisbase,'include','grass','confparms.h')
  789. filebuild = open(build)
  790. val = filebuild.readline()
  791. filebuild.close()
  792. sys.stdout.write("%s\n" % val.strip().strip('"').strip())
  793. elif arg == 'compiler':
  794. val = grep('CC',linesplat)
  795. sys.stdout.write("%s\n" % val[0].split('=')[1].strip())
  796. elif arg == 'revision':
  797. rev = os.path.join(gisbase,'include','grass','gis.h')
  798. filerev = open(rev)
  799. linesrev = filerev.readlines()
  800. val = grep('#define GIS_H_VERSION', linesrev)
  801. filerev.close()
  802. sys.stdout.write("%s\n" % val[0].split(':')[1].rstrip('$"\n').strip())
  803. else:
  804. message(_("Parameter <%s> not supported") % arg)
  805. def get_username():
  806. global user
  807. if windows:
  808. user = os.getenv('USERNAME')
  809. if not user:
  810. user = "user_name"
  811. else:
  812. user = os.getenv('USER')
  813. if not user:
  814. user = os.getenv('LOGNAME')
  815. if not user:
  816. try:
  817. p = Popen(['whoami'], stdout = subprocess.PIPE)
  818. s = p.stdout.read()
  819. p.wait()
  820. user = s.strip()
  821. except:
  822. pass
  823. if not user:
  824. user = "user_%d" % os.getuid()
  825. def parse_cmdline():
  826. global args, grass_gui, create_new
  827. args = []
  828. for i in sys.argv[1:]:
  829. # Check if the user asked for the version
  830. if i in ["-v", "--version"]:
  831. message('\n' + readfile(gfile("etc", "license")))
  832. sys.exit()
  833. # Check if the user asked for help
  834. elif i in ["help", "-h", "-help", "--help"]:
  835. help_message()
  836. sys.exit()
  837. # Check if the -text flag was given
  838. elif i in ["-text", "--text"]:
  839. grass_gui = 'text'
  840. # Check if the -gui flag was given
  841. elif i in ["-gui", "--gui"]:
  842. grass_gui = default_gui
  843. # Check if the -wxpython flag was given
  844. elif i in ["-wxpython", "-wx", "--wxpython", "--wx"]:
  845. grass_gui = 'wxpython'
  846. # Check if the user wants to create a new mapset
  847. elif i == "-c":
  848. create_new = True
  849. elif i == "--config":
  850. print_params()
  851. sys.exit()
  852. else:
  853. args.append(i)
  854. ### MAIN script starts here
  855. # Get the system name
  856. windows = sys.platform == 'win32'
  857. cygwin = "cygwin" in sys.platform
  858. macosx = "darwin" in sys.platform
  859. # Set GISBASE
  860. os.environ['GISBASE'] = gisbase
  861. # set HOME
  862. if windows and not os.getenv('HOME'):
  863. os.environ['HOME'] = os.path.join(os.getenv('HOMEDRIVE'), os.getenv('HOMEPATH'))
  864. # set SHELL
  865. if windows:
  866. if os.getenv('GRASS_SH'):
  867. os.environ['SHELL'] = os.getenv('GRASS_SH')
  868. if not os.getenv('SHELL'):
  869. os.environ['SHELL'] = os.getenv('COMSPEC', 'cmd.exe')
  870. atexit.register(cleanup)
  871. # Set default GUI
  872. default_gui = "wxpython"
  873. # the following is only meant to be an internal variable for debugging this script.
  874. # use 'g.gisenv set="DEBUG=[0-5]"' to turn GRASS debug mode on properly.
  875. grass_debug = os.getenv('GRASS_DEBUG')
  876. # Set GRASS version number for R interface etc (must be an env_var for MS-Windows)
  877. os.environ['GRASS_VERSION'] = grass_version
  878. # Set the GIS_LOCK variable to current process id
  879. gis_lock = str(os.getpid())
  880. os.environ['GIS_LOCK'] = gis_lock
  881. # Set the global grassrc file
  882. batch_job = os.getenv('GRASS_BATCH_JOB')
  883. if batch_job:
  884. gisrcrc = os.path.join(grass_config_dir, "rc.%s" % platform.node())
  885. if not os.access(gisrcrc, os.R_OK):
  886. gisrcrc = os.path.join(grass_config_dir, "rc")
  887. else:
  888. gisrcrc = os.path.join(grass_config_dir, "rc")
  889. # Set the username and working directory
  890. get_username()
  891. # Parse the command-line options
  892. parse_cmdline()
  893. # Create the temporary directory and session grassrc file
  894. create_tmp()
  895. # Create the session grassrc file
  896. create_gisrc()
  897. # Ensure GUI is set
  898. read_gui()
  899. # Get environmental variables from gisenv variables
  900. set_env_from_gisrc()
  901. # Get Locale name
  902. get_locale()
  903. # Set PATH, PYTHONPATH
  904. set_paths()
  905. # Set LD_LIBRARY_PATH (etc) to find GRASS shared libraries
  906. path_prepend(gfile("lib"), ld_library_path_var)
  907. # Set GRASS_PAGER, GRASS_WISH, GRASS_PYTHON, GRASS_GNUPLOT, GRASS_PROJSHARE
  908. set_defaults()
  909. # Set GRASS_HTML_BROWSER
  910. set_browser()
  911. #predefine monitor size for certain architectures
  912. if os.getenv('HOSTTYPE') == 'arm':
  913. # small monitor on ARM (iPAQ, zaurus... etc)
  914. os.environ['GRASS_HEIGHT'] = "320"
  915. os.environ['GRASS_WIDTH'] = "240"
  916. # First time user - GISRC is defined in the GRASS script
  917. if not os.access(gisrc, os.F_OK):
  918. if grass_gui == 'text' and len(args) == 0:
  919. fatal(_("Unable to start GRASS. You can:\n"
  920. " - Launch GRASS with '-gui' switch (`grass70 -gui`)\n"
  921. " - Create manually GISRC file (%s)\n"
  922. " - Launch GRASS with path to "
  923. "the location/mapset as an argument (`grass70 /path/to/location/mapset`)") % gisrcrc)
  924. grass_intro()
  925. else:
  926. clean_temp()
  927. message(_("Starting GRASS GIS..."))
  928. # Check that the GUI works
  929. check_gui()
  930. # Parsing argument to get LOCATION
  931. if not args:
  932. # Try interactive startup
  933. location = None
  934. else:
  935. if create_new:
  936. if len(args) > 1:
  937. non_interactive(args[1], args[0])
  938. else:
  939. non_interactive(args[0])
  940. else:
  941. non_interactive(args[0])
  942. # User selects LOCATION and MAPSET if not set
  943. set_data()
  944. # Set GISDBASE, LOCATION_NAME, MAPSET, LOCATION from $GISRC
  945. load_gisrc()
  946. # Check .gislock file
  947. check_lock()
  948. # build user fontcap if specified but not present
  949. make_fontcap()
  950. # predefine default driver if DB connection not defined
  951. # is this really needed?? Modules should call this when/if required.
  952. if not os.access(os.path.join(location, "VAR"), os.F_OK):
  953. call(['db.connect', '-c', '--quiet'])
  954. check_shell()
  955. check_batch_job()
  956. if not batch_job:
  957. start_gui()
  958. clear_screen()
  959. # Display the version and license info
  960. if batch_job:
  961. say_hello()
  962. grass_gui = 'text'
  963. clear_screen()
  964. clean_temp()
  965. try_remove(lockfile)
  966. sys.exit(0)
  967. else:
  968. show_banner()
  969. say_hello()
  970. show_info()
  971. if grass_gui == "wxpython":
  972. message(_("Launching <%s> GUI in the background, please wait...") % grass_gui)
  973. if sh in ['csh', 'tcsh']:
  974. csh_startup()
  975. elif sh in ['bash', 'msh', 'cygwin']:
  976. bash_startup()
  977. else:
  978. default_startup()
  979. clear_screen()
  980. clean_env()
  981. clean_temp()
  982. try_remove(lockfile)
  983. # Save GISRC
  984. s = readfile(gisrc)
  985. if not os.path.exists(grass_config_dir):
  986. os.mkdir(grass_config_dir)
  987. writefile(gisrcrc, s)
  988. cleanup()
  989. # After this point no more grass modules may be called
  990. done_message()