grass.py 28 KB

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