grass.py 26 KB

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