grass.py 33 KB

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