grass.py 26 KB

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