grass.py 33 KB

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