grass.py 30 KB

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