grass.py 26 KB

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