grass.py 33 KB

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