grass.py 32 KB

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