grass.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  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 (based on init.sh) by Glynn Clements
  12. # PURPOSE: Sets up some environment variables.
  13. # It also parses any remaining command line options for
  14. # setting the GISDBASE, LOCATION, and/or MAPSET.
  15. # Finally it starts GRASS with the appropriate user
  16. # interface and cleans up after it is finished.
  17. # COPYRIGHT: (C) 2000-2010 by the GRASS Development Team
  18. #
  19. # This program is free software under the GNU General
  20. # Public License (>=v2). Read the file COPYING that
  21. # comes with GRASS for details.
  22. #
  23. #############################################################################
  24. import sys
  25. import os
  26. import atexit
  27. import string
  28. import subprocess
  29. # Variables substituted during build process
  30. # Set the GISBASE variable
  31. gisbase = "@GISBASE@"
  32. cmd_name = "@START_UP@"
  33. grass_version = "@GRASS_VERSION_NUMBER@"
  34. ld_library_path_var = '@LD_LIBRARY_PATH_VAR@'
  35. config_projshare = "@CONFIG_PROJSHARE@"
  36. grass_config_dirname = "@GRASS_CONFIG_DIR@"
  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 not kv.has_key('GRASS_GUI'):
  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", "gui", "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. if not mapset:
  358. l, mapset = os.path.split(l)
  359. l, location_name = os.path.split(l)
  360. gisdbase = l
  361. if gisdbase and location_name and mapset:
  362. location = os.path.join(gisdbase, location_name, mapset)
  363. if not os.access(os.path.join(location, "WIND"), os.R_OK):
  364. if location_name == "PERMANENT":
  365. fatal("%s: Not a valid GRASS location" % location)
  366. else:
  367. # the user wants to create mapset on the fly
  368. if create_new:
  369. if not os.access(os.path.join(os.path.join(gisdbase, location_name, "PERMANENT", "DEFAULT_WIND")), os.F_OK):
  370. fatal("The LOCATION \"%s\" does not exist. Please create it first" % location_name)
  371. else:
  372. os.mkdirs(location)
  373. # copy PERMANENT/DEFAULT_WIND to <mapset>/WIND
  374. s = readfile(os.path.join(gisdbase, location_name, "PERMANENT", "DEFAULT_WIND"))
  375. writefile(os.path.join(location, "WIND"), s)
  376. message("Missing WIND file fixed")
  377. else:
  378. fatal("%s: Not a valid GRASS location" % location)
  379. if os.access(gisrc, os.R_OK):
  380. kv = read_gisrc()
  381. else:
  382. kv = {}
  383. kv['GISDBASE'] = gisdbase
  384. kv['LOCATION_NAME'] = location_name
  385. kv['MAPSET'] = mapset
  386. write_gisrc(kv)
  387. else:
  388. fatal("GISDBASE, LOCATION_NAME and MAPSET variables not set properly.\n" +
  389. "Interactive startup needed.")
  390. def set_data():
  391. # User selects LOCATION and MAPSET if not set
  392. if not location:
  393. # Check for text interface
  394. if grass_gui == 'text':
  395. pass
  396. # Check for GUI
  397. elif grass_gui == 'wxpython':
  398. gui_startup()
  399. else:
  400. # Shouldn't need this but you never know
  401. fatal("ERROR: Invalid user interface specified - <%s>.\n" % grass_gui +
  402. "Use the --help option to see valid interface names.")
  403. def gui_startup():
  404. if grass_gui == 'wxpython':
  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 == 2:
  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. subprocess.Popen([os.getenv('GRASS_PYTHON'),
  515. gfile(wxpython_base, "wxgui.py")])
  516. def clear_screen():
  517. if windows:
  518. pass
  519. # TODO: uncomment when PDCurses works.
  520. # cls
  521. else:
  522. if not os.getenv('GRASS_BATCH_JOB') and not grass_debug:
  523. call(["tput", "clear"])
  524. def show_banner():
  525. sys.stderr.write(r"""
  526. __________ ___ __________ _______________
  527. / ____/ __ \/ | / ___/ ___/ / ____/ _/ ___/
  528. / / __/ /_/ / /| | \__ \\_ \ / / __ / / \__ \
  529. / /_/ / _, _/ ___ |___/ /__/ / / /_/ // / ___/ /
  530. \____/_/ |_/_/ |_/____/____/ \____/___//____/
  531. """)
  532. def say_hello():
  533. if locale:
  534. path = gfile("locale", locale, "etc", "welcome")
  535. if not os.access(path, os.R_OK):
  536. path = gfile("etc", "welcome")
  537. else:
  538. path = gfile("etc", "welcome")
  539. s = readfile(path)
  540. sys.stderr.write(s)
  541. def show_info():
  542. sys.stderr.write(
  543. r"""
  544. GRASS homepage: http://grass.osgeo.org/
  545. This version running through: %s (%s)
  546. Help is available with the command: g.manual -i
  547. See the licence terms with: g.version -c
  548. """ % (shellname, os.getenv('SHELL')))
  549. if grass_gui == 'wxpython':
  550. message("If required, restart the GUI with: g.gui wxpython")
  551. else:
  552. message("Start the GUI with: g.gui %s" % default_gui)
  553. message("When ready to quit enter: exit")
  554. message("")
  555. def csh_startup():
  556. global exit_val
  557. userhome = os.getenv('HOME') # save original home
  558. home = location
  559. os.environ['HOME'] = home
  560. cshrc = os.path.join(home, ".cshrc")
  561. tcshrc = os.path.join(home, ".tcshrc")
  562. try_remove(cshrc)
  563. try_remove(tcshrc)
  564. f = open(cshrc, 'w')
  565. f.write("set home = %s" % userhome)
  566. f.write("set history = 3000 savehist = 3000 noclobber ignoreeof")
  567. f.write("set histfile = %s" % os.path.join(os.getenv('HOME'), ".history"))
  568. f.write("set prompt = '\\")
  569. f.write("Mapset <%s> in Location <%s> \\" % (mapset, location_name))
  570. f.write("GRASS %s > '" % grass_version)
  571. f.write("set BOGUS=``;unset BOGUS")
  572. path = os.path.join(userhome, ".grass.cshrc")
  573. if os.access(path, os.R_OK):
  574. f.write(readfile(path))
  575. mail_re = re.compile(r"^ *set *mail *= *")
  576. for filename in [".cshrc", ".tcshrc", ".login"]:
  577. path = os.path.join(userhome, filename)
  578. if os.access(path, os.R_OK):
  579. s = readfile(path)
  580. lines = s.splitlines()
  581. for l in lines:
  582. if mail_re.match(l):
  583. f.write(l)
  584. path = os.getenv('PATH').split(':')
  585. f.write("set path = ( %s ) " % ' '.join(path))
  586. f.close()
  587. writefile(tcshrc, readfile(cshrc))
  588. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  589. os.environ['HOME'] = userhome
  590. def bash_startup():
  591. global exit_val
  592. # save command history in mapset dir and remember more
  593. os.environ['HISTFILE'] = os.path.join(location, ".bash_history")
  594. if not os.getenv('HISTSIZE') and not os.getenv('HISTFILESIZE'):
  595. os.environ['HISTSIZE'] = "3000"
  596. # instead of changing $HOME, start bash with: --rcfile "$LOCATION/.bashrc" ?
  597. # if so, must care be taken to explicity call .grass.bashrc et al for
  598. # non-interactive bash batch jobs?
  599. userhome = os.getenv('HOME') # save original home
  600. home = location # save .bashrc in $LOCATION
  601. os.environ['HOME'] = home
  602. bashrc = os.path.join(home, ".bashrc")
  603. try_remove(bashrc)
  604. f = open(bashrc, 'w')
  605. f.write("test -r ~/.alias && . ~/.alias\n")
  606. f.write("PS1='GRASS %s (%s):\w > '\n" % (grass_version, location_name))
  607. f.write("PROMPT_COMMAND=%s\n" % gfile("etc", "prompt.sh"))
  608. path = os.path.join(userhome, ".grass.bashrc")
  609. if os.access(path, os.R_OK):
  610. f.write(readfile(path) + '\n')
  611. f.write("export PATH=\"%s\"\n" % os.getenv('PATH'))
  612. f.write("export HOME=\"%s\"\n" % userhome) # restore user home path
  613. f.close()
  614. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  615. os.environ['HOME'] = userhome
  616. def default_startup():
  617. global exit_val
  618. if windows:
  619. os.environ['PS1'] = "GRASS %s> " % (grass_version)
  620. # "$ETC/run" doesn't work at all???
  621. exit_val = call([os.getenv('SHELL')])
  622. cleanup_dir(os.path.join(location, ".tmp")) # remove GUI session files from .tmp
  623. else:
  624. os.environ['PS1'] = "GRASS %s (%s):\w > " % (grass_version, location_name)
  625. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  626. def done_message():
  627. if batch_job and os.access(batch_job, os.X_OK):
  628. message("Batch job '%s' (defined in GRASS_BATCH_JOB variable) was executed." % batch_job)
  629. message("Goodbye from GRASS GIS")
  630. sys.exit(exit_val)
  631. else:
  632. message("Done.")
  633. message("")
  634. message("Goodbye from GRASS GIS")
  635. message("")
  636. def clean_temp():
  637. message("Cleaning up temporary files ...")
  638. nul = open(os.devnull, 'w')
  639. call([gfile("etc", "clean_temp")], stdout = nul, stderr = nul)
  640. nul.close()
  641. def get_username():
  642. global user
  643. if windows:
  644. user = os.getenv('USERNAME')
  645. if not user:
  646. user = "user_name"
  647. else:
  648. user = os.getenv('USER')
  649. if not user:
  650. user = os.getenv('LOGNAME')
  651. if not user:
  652. try:
  653. p = subprocess.Popen(['whoami'], stdout = subprocess.PIPE)
  654. s = p.stdout.read()
  655. p.wait()
  656. user = s.strip()
  657. except:
  658. pass
  659. if not user:
  660. user = "user_%d" % os.getuid()
  661. def parse_cmdline():
  662. global args, grass_gui, create_new
  663. args = []
  664. for i in sys.argv[1:]:
  665. # Check if the user asked for the version
  666. if i in ["-v","--version"]:
  667. message(readfile(gfile("etc", "license")))
  668. sys.exit()
  669. # Check if the user asked for help
  670. elif i in ["help","-h","-help","--help"]:
  671. help_message()
  672. sys.exit()
  673. # Check if the -text flag was given
  674. elif i == "-text":
  675. grass_gui = 'text'
  676. # Check if the -gui flag was given
  677. elif i == "-gui":
  678. grass_gui = default_gui
  679. # Check if the -wxpython flag was given
  680. elif i in ["-wxpython","-wx"]:
  681. grass_gui = 'wxpython'
  682. # Check if the user wants to create a new mapset
  683. elif i == "-c":
  684. create_new = True
  685. else:
  686. args.append(i)
  687. ### MAIN script starts here
  688. # Get the system name
  689. windows = sys.platform == 'win32'
  690. cygwin = "cygwin" in sys.platform
  691. macosx = "darwin" in sys.platform
  692. # Set GISBASE
  693. os.environ['GISBASE'] = gisbase
  694. # set HOME
  695. if windows and not os.getenv('HOME'):
  696. os.environ['HOME'] = os.path.join(os.getenv('HOMEDRIVE'), os.getenv('HOMEPATH'))
  697. # set SHELL
  698. if windows and not os.getenv('SHELL'):
  699. os.environ['SHELL'] = os.getenv('COMSPEC', 'cmd.exe')
  700. grass_config_dir = os.path.join(os.getenv('HOME'), grass_config_dirname)
  701. atexit.register(cleanup)
  702. # Set default GUI
  703. default_gui = "wxpython"
  704. # the following is only meant to be an internal variable for debugging this script.
  705. # use 'g.gisenv set="DEBUG=[0-5]"' to turn GRASS debug mode on properly.
  706. grass_debug = os.getenv('GRASS_DEBUG')
  707. # GRASS_SH is normally just for Windows when not started from a bourne
  708. # shell. But when starting from Init.sh is still needed for GRASS_GUI (still true for GRASS 7?)
  709. os.environ['GRASS_SH'] = "/bin/sh"
  710. # Set GRASS version number for R interface etc (must be an env_var for MS-Windows)
  711. os.environ['GRASS_VERSION'] = grass_version
  712. # Set the GIS_LOCK variable to current process id
  713. gis_lock = str(os.getpid())
  714. os.environ['GIS_LOCK'] = gis_lock
  715. # Set the global grassrc file
  716. batch_job = os.getenv('GRASS_BATCH_JOB')
  717. if batch_job:
  718. gisrcrc = os.path.join(grass_config_dir, "rc.%s" % os.uname()[1])
  719. if not os.access(gisrcrc, os.R_OK):
  720. gisrcrc = os.path.join(grass_config_dir, "rc")
  721. else:
  722. gisrcrc = os.path.join(grass_config_dir, "rc")
  723. # Set the username and working directory
  724. get_username()
  725. # Parse the command-line options
  726. parse_cmdline()
  727. # Create the temporary directory and session grassrc file
  728. create_tmp()
  729. # Create the session grassrc file
  730. create_gisrc()
  731. # Ensure GRASS_GUI is set
  732. read_gui()
  733. # Get Locale name
  734. get_locale()
  735. # Set PATH, PYTHONPATH
  736. set_paths()
  737. # Set LD_LIBRARY_PATH (etc) to find GRASS shared libraries
  738. path_prepend(gfile("lib"), ld_library_path_var)
  739. # Set GRASS_PAGER, GRASS_WISH, GRASS_PYTHON, GRASS_GNUPLOT, GRASS_PROJSHARE
  740. set_defaults()
  741. # Set GRASS_HTML_BROWSER
  742. set_browser()
  743. #predefine monitor size for certain architectures
  744. if os.getenv('HOSTTYPE') == 'arm':
  745. #small monitor on ARM (iPAQ, zaurus... etc)
  746. os.environ['GRASS_HEIGHT'] = "320"
  747. os.environ['GRASS_WIDTH'] = "240"
  748. # First time user - GISRC is defined in the GRASS script
  749. if not os.access(gisrc, os.F_OK):
  750. grass_intro()
  751. else:
  752. clean_temp()
  753. message("Starting GRASS ...")
  754. # Check that the GUI works
  755. check_gui()
  756. # Parsing argument to get LOCATION
  757. if args == []:
  758. # Try interactive startup
  759. location = None
  760. else:
  761. non_interactive(args[0])
  762. # User selects LOCATION and MAPSET if not set
  763. set_data()
  764. # Set GISDBASE, LOCATION_NAME, MAPSET, LOCATION from $GISRC
  765. load_gisrc()
  766. # Check .gislock file
  767. check_lock()
  768. # build user fontcap if specified but not present
  769. make_fontcap()
  770. # predefine default driver if DB connection not defined
  771. # is this really needed?? Modules should call this when/if required.
  772. if not os.access(os.path.join(location, "VAR"), os.F_OK):
  773. call(['db.connect', '-c', '--quiet'])
  774. check_shell()
  775. check_batch_job()
  776. start_gui()
  777. clear_screen()
  778. # Display the version and license info
  779. if batch_job:
  780. say_hello()
  781. else:
  782. show_banner()
  783. say_hello()
  784. show_info()
  785. if sh in ['csh', 'tcsh']:
  786. csh_startup()
  787. elif sh in ['bash', 'msh', 'cygwin']:
  788. bash_startup()
  789. else:
  790. default_startup()
  791. clear_screen()
  792. clean_temp()
  793. try_remove(lockfile)
  794. # Save GISRC
  795. s = readfile(gisrc)
  796. if not os.path.exists(grass_config_dir):
  797. os.mkdir(grass_config_dir)
  798. writefile(gisrcrc, s)
  799. cleanup()
  800. #### after this point no more grass modules may be called ####
  801. done_message()