grass.py 32 KB

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