grass.py 26 KB

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