grass.py 28 KB

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