grass.py 34 KB

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