grass.py 31 KB

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