grass.py 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496
  1. #!/usr/bin/env python
  2. #############################################################################
  3. #
  4. # MODULE: GRASS initialization script
  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. #
  12. # GRASS 7: converted to Python (based on init.sh shell
  13. # script from GRASS 6) by Glynn Clements
  14. # Martin Landa <landa.martin gmail.com>
  15. # Luca Delucchi <lucadeluge gmail.com>
  16. # PURPOSE: Sets up environment variables, parses any remaining
  17. # command line options for setting the GISDBASE, LOCATION,
  18. # and/or MAPSET. Finally it starts GRASS with the appropriate
  19. # user interface and cleans up after it is finished.
  20. # COPYRIGHT: (C) 2000-2015 by the GRASS Development Team
  21. #
  22. # This program is free software under the GNU General
  23. # Public License (>=v2). Read the file COPYING that
  24. # comes with GRASS for details.
  25. #
  26. #############################################################################
  27. import sys
  28. import os
  29. import atexit
  30. import string
  31. import subprocess
  32. import re
  33. import platform
  34. import tempfile
  35. # Variables substituted during build process
  36. if 'GISBASE' in os.environ:
  37. gisbase = os.environ['GISBASE']
  38. else:
  39. gisbase = "@GISBASE@"
  40. cmd_name = "@START_UP@"
  41. grass_version = "@GRASS_VERSION_NUMBER@"
  42. ld_library_path_var = '@LD_LIBRARY_PATH_VAR@'
  43. if 'GRASS_PROJSHARE' in os.environ:
  44. config_projshare = os.environ['GRASS_PROJSHARE']
  45. else:
  46. config_projshare = "@CONFIG_PROJSHARE@"
  47. # configuration directory
  48. grass_env_file = None # see check_shell()
  49. if sys.platform == 'win32':
  50. grass_config_dirname = "GRASS7"
  51. grass_config_dir = os.path.join(os.getenv('APPDATA'), grass_config_dirname)
  52. else:
  53. grass_config_dirname = ".grass7"
  54. grass_config_dir = os.path.join(os.getenv('HOME'), grass_config_dirname)
  55. gisbase = os.path.normpath(gisbase)
  56. # i18N
  57. import gettext
  58. gettext.install('grasslibs', os.path.join(gisbase, 'locale'), unicode=True)
  59. tmpdir = None
  60. lockfile = None
  61. remove_lockfile = True
  62. location = None
  63. create_new = None
  64. grass_gui = None
  65. exit_grass = None
  66. force_gislock_removal = None
  67. encoding = None
  68. def warning(text):
  69. sys.stderr.write(_("WARNING") + ': ' + text + os.linesep)
  70. def try_remove(path):
  71. try:
  72. os.remove(path)
  73. except:
  74. pass
  75. def try_rmdir(path):
  76. try:
  77. os.rmdir(path)
  78. except:
  79. pass
  80. def clean_env():
  81. env_curr = read_gisrc()
  82. env_new = {}
  83. for k,v in env_curr.iteritems():
  84. if 'MONITOR' not in k:
  85. env_new[k] = v
  86. write_gisrc(env_new)
  87. def cleanup_dir(path):
  88. if not path:
  89. return
  90. for root, dirs, files in os.walk(path, topdown=False):
  91. for name in files:
  92. try_remove(os.path.join(root, name))
  93. for name in dirs:
  94. try_rmdir(os.path.join(root, name))
  95. def cleanup():
  96. tmpdir, lockfile, remove_lockfile
  97. # all exits after setting up tmp dirs (system/location) should
  98. # also tidy it up
  99. cleanup_dir(tmpdir)
  100. try_rmdir(tmpdir)
  101. if location:
  102. tmpdir_loc = os.path.join(location, ".tmp")
  103. cleanup_dir(tmpdir_loc)
  104. try_rmdir(tmpdir_loc)
  105. # remove lock-file if requested
  106. if lockfile and remove_lockfile:
  107. try_remove(lockfile)
  108. def fatal(msg):
  109. sys.stderr.write("%s: " % _('ERROR') + msg + os.linesep)
  110. sys.exit(_("Exiting..."))
  111. def message(msg):
  112. sys.stderr.write(msg + "\n")
  113. sys.stderr.flush()
  114. def readfile(path):
  115. f = open(path, 'r')
  116. s = f.read()
  117. f.close()
  118. return s
  119. def writefile(path, s):
  120. f = open(path, 'w')
  121. f.write(s)
  122. f.close()
  123. def call(cmd, **kwargs):
  124. if windows:
  125. kwargs['shell'] = True
  126. return subprocess.call(cmd, **kwargs)
  127. def Popen(cmd, **kwargs):
  128. if windows:
  129. kwargs['shell'] = True
  130. return subprocess.Popen(cmd, **kwargs)
  131. def gfile(*args):
  132. return os.path.join(gisbase, *args)
  133. help_text = r"""GRASS GIS %s
  134. Geographic Resources Analysis Support System (GRASS GIS).
  135. %s:
  136. $CMD_NAME [-h | -help | --help] [-v | --version] [-c | -c geofile | -c EPSG:code[:datum_trans]]
  137. [-e] [-f] [-text | -gui] [--config param]
  138. [[[<GISDBASE>/]<LOCATION_NAME>/]<MAPSET>]
  139. %s:
  140. -h or -help or --help %s
  141. -v or --version %s
  142. -c %s
  143. -e %s
  144. -f %s
  145. -text %s
  146. %s
  147. -gtext %s
  148. %s
  149. -gui %s
  150. %s
  151. --config %s
  152. %s
  153. %s:
  154. GISDBASE %s
  155. LOCATION_NAME %s
  156. MAPSET %s
  157. GISDBASE/LOCATION_NAME/MAPSET %s
  158. %s:
  159. GRASS_GUI %s
  160. GRASS_HTML_BROWSER %s
  161. GRASS_ADDON_PATH %s
  162. GRASS_ADDON_BASE %s
  163. GRASS_BATCH_JOB %s
  164. GRASS_PYTHON %s
  165. """ % (grass_version,
  166. _("Usage"),
  167. _("Flags"),
  168. _("print this help message"),
  169. _("show version information and exit"),
  170. _("create given database, location or mapset if it doesn't exist"),
  171. _("exit after creation of location or mapset. Only with -c flag"),
  172. _("force removal of .gislock if exists (use with care!). Only with -text flag"),
  173. _("use text based interface (skip welcome screen)"),
  174. _("and set as default"),
  175. _("use text based interface (show welcome screen)"),
  176. _("and set as default"),
  177. _("use $DEFAULT_GUI graphical user interface"),
  178. _("and set as default"),
  179. _("print GRASS configuration parameters"),
  180. _("options: arch,build,compiler,path,revision"),
  181. _("Parameters"),
  182. _("initial database (path to GIS data)"),
  183. _("initial location"),
  184. _("initial mapset"),
  185. _("fully qualified initial mapset directory"),
  186. _("Environment variables relevant for startup"),
  187. _("select GUI (text, gui)"),
  188. _("set html web browser for help pages"),
  189. _("set additional path(s) to local GRASS modules or user scripts"),
  190. _("set additional GISBASE for locally installed GRASS Addons"),
  191. _("shell script to be processed as batch job"),
  192. _("set python shell name to override 'python'"))
  193. def help_message():
  194. t = string.Template(help_text)
  195. s = t.substitute(CMD_NAME=cmd_name, DEFAULT_GUI=default_gui)
  196. sys.stderr.write(s)
  197. def create_tmp():
  198. global tmpdir
  199. ## use $TMPDIR if it exists, then $TEMP, otherwise /tmp
  200. tmp = os.getenv('TMPDIR')
  201. if not tmp:
  202. tmp = os.getenv('TEMP')
  203. if not tmp:
  204. tmp = os.getenv('TMP')
  205. if not tmp:
  206. tmp = tempfile.gettempdir()
  207. if tmp:
  208. tmpdir = os.path.join(tmp, "grass7-%(user)s-%(lock)s" % {'user': user,
  209. 'lock': gis_lock})
  210. try:
  211. os.mkdir(tmpdir, 0700)
  212. except:
  213. tmp = None
  214. if not tmp:
  215. for ttmp in ("/tmp", "/var/tmp", "/usr/tmp"):
  216. tmp = ttmp
  217. tmpdir = os.path.join(tmp, "grass7-%(user)s-%(lock)s" % {
  218. 'user': user, 'lock': gis_lock})
  219. try:
  220. os.mkdir(tmpdir, 0700)
  221. except:
  222. tmp = None
  223. if tmp:
  224. break
  225. if not tmp:
  226. fatal(_("Unable to create temporary directory <grass7-%(user)s-" \
  227. "%(lock)s>! Exiting.") % {'user': user, 'lock': gis_lock})
  228. def create_gisrc():
  229. global gisrc, gisrcrc
  230. # Set the session grassrc file
  231. gisrc = os.path.join(tmpdir, "gisrc")
  232. os.environ['GISRC'] = gisrc
  233. # remove invalid GISRC file to avoid disturbing error messages:
  234. try:
  235. s = readfile(gisrcrc)
  236. if "UNKNOWN" in s:
  237. try_remove(gisrcrc)
  238. s = None
  239. except:
  240. s = None
  241. # Copy the global grassrc file to the session grassrc file
  242. if s:
  243. writefile(gisrc, s)
  244. def read_gisrc():
  245. kv = {}
  246. try:
  247. f = open(gisrc, 'r')
  248. except IOError:
  249. return kv
  250. for line in f:
  251. k, v = line.split(':', 1)
  252. kv[k.strip()] = v.strip()
  253. f.close()
  254. return kv
  255. def read_env_file(path):
  256. kv = {}
  257. f = open(path, 'r')
  258. for line in f:
  259. k, v = line.split(':', 1)
  260. kv[k.strip()] = v.strip()
  261. f.close()
  262. return kv
  263. def write_gisrc(kv):
  264. f = open(gisrc, 'w')
  265. for k, v in kv.iteritems():
  266. f.write("%s: %s\n" % (k, v))
  267. f.close()
  268. def read_gui():
  269. global grass_gui
  270. # At this point the GRASS user interface variable has been set from the
  271. # command line, been set from an external environment variable, or is
  272. # not set. So we check if it is not set
  273. if not grass_gui:
  274. # Check for a reference to the GRASS user interface in the grassrc file
  275. if os.access(gisrc, os.R_OK):
  276. kv = read_gisrc()
  277. if 'GRASS_GUI' in os.environ:
  278. grass_gui = os.environ['GRASS_GUI']
  279. elif 'GUI' in kv:
  280. grass_gui = kv['GUI']
  281. elif 'GRASS_GUI' in kv:
  282. # For backward compatibility (GRASS_GUI renamed to GUI)
  283. grass_gui = kv['GRASS_GUI']
  284. else:
  285. # Set the GRASS user interface to the default if needed
  286. grass_gui = default_gui
  287. if not grass_gui:
  288. grass_gui = default_gui
  289. if grass_gui == 'gui':
  290. grass_gui = default_gui
  291. # FIXME oldtcltk, gis.m, d.m no longer exist
  292. if grass_gui in ['d.m', 'gis.m', 'oldtcltk', 'tcltk']:
  293. warning(_("GUI <%s> not supported in this version") % grass_gui)
  294. grass_gui = default_gui
  295. def path_prepend(dir, var):
  296. path = os.getenv(var)
  297. if path:
  298. path = dir + os.pathsep + path
  299. else:
  300. path = dir
  301. os.environ[var] = path
  302. def path_append(dir, var):
  303. path = os.getenv(var)
  304. if path:
  305. path = path + os.pathsep + dir
  306. else:
  307. path = dir
  308. os.environ[var] = path
  309. def set_paths():
  310. # addons (path)
  311. addon_path = os.getenv('GRASS_ADDON_PATH')
  312. if addon_path:
  313. for path in addon_path.split(os.pathsep):
  314. path_prepend(addon_path, 'PATH')
  315. # addons (base)
  316. addon_base = os.getenv('GRASS_ADDON_BASE')
  317. if not addon_base:
  318. addon_base = os.path.join(grass_config_dir, 'addons')
  319. os.environ['GRASS_ADDON_BASE'] = addon_base
  320. if not windows:
  321. path_prepend(os.path.join(addon_base, 'scripts'), 'PATH')
  322. path_prepend(os.path.join(addon_base, 'bin'), 'PATH')
  323. # standard installation
  324. if not windows:
  325. path_prepend(gfile('scripts'), 'PATH')
  326. path_prepend(gfile('bin'), 'PATH')
  327. # Set PYTHONPATH to find GRASS Python modules
  328. if os.path.exists(gfile('gui', 'wxpython')):
  329. path_prepend(gfile('gui', 'wxpython'), 'PYTHONPATH')
  330. if os.path.exists(gfile('etc', 'python')):
  331. path_prepend(gfile('etc', 'python'), 'PYTHONPATH')
  332. # set path for the GRASS man pages
  333. grass_man_path = os.path.join(gisbase, 'docs', 'man')
  334. addons_man_path = os.path.join(addon_base, 'docs', 'man')
  335. man_path = os.getenv('MANPATH')
  336. sys_man_path = None
  337. if man_path:
  338. path_prepend(addons_man_path, 'MANPATH')
  339. path_prepend(grass_man_path, 'MANPATH')
  340. else:
  341. try:
  342. nul = open(os.devnull, 'w')
  343. p = Popen(['manpath'], stdout=subprocess.PIPE, stderr=nul)
  344. nul.close()
  345. s = p.stdout.read()
  346. p.wait()
  347. sys_man_path = s.strip()
  348. except:
  349. pass
  350. if sys_man_path:
  351. os.environ['MANPATH'] = sys_man_path
  352. path_prepend(addons_man_path, 'MANPATH')
  353. path_prepend(grass_man_path, 'MANPATH')
  354. else:
  355. os.environ['MANPATH'] = addons_man_path
  356. path_prepend(grass_man_path, 'MANPATH')
  357. def find_exe(pgm):
  358. for dir in os.getenv('PATH').split(os.pathsep):
  359. path = os.path.join(dir, pgm)
  360. if os.access(path, os.X_OK):
  361. return path
  362. return None
  363. def set_defaults():
  364. # GRASS_PAGER
  365. if not os.getenv('GRASS_PAGER'):
  366. if find_exe("more"):
  367. pager = "more"
  368. elif find_exe("less"):
  369. pager = "less"
  370. elif windows:
  371. pager = "more"
  372. else:
  373. pager = "cat"
  374. os.environ['GRASS_PAGER'] = pager
  375. # GRASS_PYTHON
  376. if not os.getenv('GRASS_PYTHON'):
  377. if windows:
  378. os.environ['GRASS_PYTHON'] = "python.exe"
  379. else:
  380. os.environ['GRASS_PYTHON'] = "python"
  381. # GRASS_GNUPLOT
  382. if not os.getenv('GRASS_GNUPLOT'):
  383. os.environ['GRASS_GNUPLOT'] = "gnuplot -persist"
  384. # GRASS_PROJSHARE
  385. if not os.getenv('GRASS_PROJSHARE'):
  386. os.environ['GRASS_PROJSHARE'] = config_projshare
  387. def set_browser():
  388. # GRASS_HTML_BROWSER
  389. browser = os.getenv('GRASS_HTML_BROWSER')
  390. if not browser:
  391. if macosx:
  392. # OSX doesn't execute browsers from the shell PATH - route thru a
  393. # script
  394. browser = gfile('etc', "html_browser_mac.sh")
  395. os.environ['GRASS_HTML_BROWSER_MACOSX'] = "-b com.apple.helpviewer"
  396. if windows or cygwin:
  397. # MinGW startup moved to into init.bat
  398. browser = "explorer"
  399. else:
  400. # the usual suspects
  401. browsers = ["xdg-open", "htmlview", "konqueror", "mozilla",
  402. "mozilla-firefox", "firefox", "iceweasel", "opera",
  403. "netscape", "dillo", "lynx", "links", "w3c"]
  404. for b in browsers:
  405. if find_exe(b):
  406. browser = b
  407. break
  408. elif macosx:
  409. # OSX doesn't execute browsers from the shell PATH - route thru a
  410. # script
  411. os.environ['GRASS_HTML_BROWSER_MACOSX'] = "-b %s" % browser
  412. browser = gfile('etc', "html_browser_mac.sh")
  413. if not browser:
  414. warning(_("Searched for a web browser, but none found"))
  415. # even so we set konqueror to make lib/gis/parser.c happy:
  416. browser = "konqueror"
  417. os.environ['GRASS_HTML_BROWSER'] = browser
  418. def grass_intro():
  419. intro = _(r"""
  420. WELCOME TO GRASS %s
  421. 1) Have at your side all available GRASS GIS tutorials
  422. 2) When working on your location, the following materials
  423. are extremely useful:
  424. - A topographic map of your area
  425. - Current catalog of available computer maps
  426. 3) Check the GRASS GIS web pages for supporting mailing lists and more:
  427. http://grass.osgeo.org
  428. """) % grass_version
  429. sys.stderr.write(intro)
  430. sys.stderr.write("\n")
  431. sys.stderr.write(_("Hit RETURN to continue"))
  432. sys.stdin.readline()
  433. # for convenience, define pwd as GISDBASE:
  434. s = r"""GISDBASE: %s
  435. LOCATION_NAME: <UNKNOWN>
  436. MAPSET: <UNKNOWN>
  437. """ % os.getcwd()
  438. writefile(gisrc, s)
  439. def check_gui():
  440. global grass_gui, wxpython_base
  441. # Check if we are running X windows by checking the DISPLAY variable
  442. if os.getenv('DISPLAY') or windows or macosx:
  443. # Check if python is working properly
  444. if grass_gui in ('wxpython', 'gtext'):
  445. nul = open(os.devnull, 'w')
  446. p = Popen([os.environ['GRASS_PYTHON']], stdin=subprocess.PIPE,
  447. stdout=nul, stderr=nul)
  448. nul.close()
  449. p.stdin.write("variable=True")
  450. p.stdin.close()
  451. p.wait()
  452. if p.returncode == 0:
  453. # Set the wxpython base directory
  454. wxpython_base = gfile("gui", "wxpython")
  455. else:
  456. # Python was not found - switch to text interface mode
  457. warning(_("The python command does not work as expected!\n"
  458. "Please check your GRASS_PYTHON environment variable.\n"
  459. "Use the -help option for details.\n"
  460. "Switching to text based interface mode.\n\n"
  461. "Hit RETURN to continue.\n"))
  462. sys.stdin.readline()
  463. grass_gui = 'text'
  464. else:
  465. # Display a message if a graphical interface was expected
  466. if grass_gui != 'text':
  467. # Set the interface mode to text
  468. warning(_("It appears that the X Windows system is not active.\n"
  469. "A graphical based user interface is not supported.\n"
  470. "Switching to text based interface mode.\n\n"
  471. "Hit RETURN to continue"""))
  472. sys.stdin.readline()
  473. grass_gui = 'text'
  474. # Save the user interface variable in the grassrc file - choose a temporary
  475. # file name that should not match another file
  476. if os.access(gisrc, os.F_OK):
  477. kv = read_gisrc()
  478. kv['GUI'] = grass_gui
  479. write_gisrc(kv)
  480. def non_interactive(arg, geofile=None):
  481. global gisdbase, location_name, mapset, location
  482. # Try non-interactive startup
  483. l = None
  484. if arg == '-':
  485. if location:
  486. l = location
  487. else:
  488. l = arg
  489. if l:
  490. if l == '.':
  491. l = os.getcwd()
  492. elif not os.path.isabs(l):
  493. l = os.path.abspath(l)
  494. l, mapset = os.path.split(l)
  495. if not mapset:
  496. l, mapset = os.path.split(l)
  497. l, location_name = os.path.split(l)
  498. gisdbase = l
  499. if gisdbase and location_name and mapset:
  500. location = os.path.join(gisdbase, location_name, mapset)
  501. # check if 'location' is a valid GRASS location/mapset
  502. if not os.access(os.path.join(location, "WIND"), os.R_OK):
  503. if not create_new:
  504. # 'location' is not valid, check if 'location_name' is
  505. # a valid GRASS location
  506. if not os.path.exists(os.path.join(gisdbase, location_name)):
  507. fatal(_("Location <%s> doesn't exist") % os.path.join(gisdbase, location_name))
  508. elif 'PERMANENT' not in os.listdir(os.path.join(gisdbase, location_name)) or \
  509. not os.path.isdir(os.path.join(gisdbase, location_name, 'PERMANENT')) or \
  510. not os.path.isfile((os.path.join(gisdbase, location_name, 'PERMANENT',
  511. 'DEFAULT_WIND'))):
  512. fatal(_("ERROR: <%s> is not a valid GRASS location") % \
  513. os.path.join(gisdbase, location_name))
  514. else:
  515. fatal(_("Mapset <%s> doesn't exist in GRASS location <%s>. "
  516. "A new mapset can be created by '-c' switch.") % (mapset, location_name))
  517. else:
  518. # 'location' is not valid, the user wants to create
  519. # mapset on the fly
  520. if not os.access(os.path.join(gisdbase, location_name,
  521. "PERMANENT",
  522. "DEFAULT_WIND"), os.F_OK):
  523. # 'location_name' is not a valid GRASS location,
  524. # create new location and 'PERMANENT' mapset
  525. gisdbase = os.path.join(gisdbase, location_name)
  526. location_name = mapset
  527. mapset = "PERMANENT"
  528. if os.access(os.path.join(os.path.join(gisdbase,
  529. location_name,
  530. "PERMANENT",
  531. "DEFAULT_WIND")),
  532. os.F_OK):
  533. fatal(_("Failed to create new location. "
  534. "The location <%s> already exists." % location_name))
  535. if gfile('etc', 'python') not in sys.path:
  536. sys.path.append(gfile('etc', 'python'))
  537. from grass.script import core as grass
  538. try:
  539. if geofile and geofile.upper().find('EPSG:') > -1:
  540. # create location using EPSG code
  541. epsg = geofile.split(':', 1)[1]
  542. if ':' in epsg:
  543. epsg, datum_trans = epsg.split(':', 1)
  544. else:
  545. datum_trans = None
  546. grass.create_location(gisdbase, location_name,
  547. epsg=epsg, datum_trans=datum_trans)
  548. else:
  549. # create location using georeferenced file
  550. grass.create_location(gisdbase, location_name,
  551. filename=geofile)
  552. except grass.ScriptError as e:
  553. fatal(e.value.strip('"').strip("'").replace('\\n',
  554. os.linesep))
  555. else:
  556. # 'location_name' is a valid GRASS location,
  557. # create new mapset
  558. os.mkdir(location)
  559. # copy PERMANENT/DEFAULT_WIND to <mapset>/WIND
  560. s = readfile(os.path.join(gisdbase, location_name,
  561. "PERMANENT", "DEFAULT_WIND"))
  562. writefile(os.path.join(location, "WIND"), s)
  563. message(_("Missing WIND file fixed"))
  564. if os.access(gisrc, os.R_OK):
  565. kv = read_gisrc()
  566. else:
  567. kv = {}
  568. kv['GISDBASE'] = gisdbase
  569. kv['LOCATION_NAME'] = location_name
  570. kv['MAPSET'] = mapset
  571. write_gisrc(kv)
  572. else:
  573. fatal(_("GISDBASE, LOCATION_NAME and MAPSET variables not set properly.\n"
  574. "Interactive startup needed."))
  575. def set_data():
  576. # User selects LOCATION and MAPSET if not set
  577. if not location:
  578. # Check for text interface
  579. if grass_gui == 'text':
  580. pass
  581. # Check for GUI
  582. elif grass_gui in ('gtext', 'wxpython'):
  583. gui_startup(grass_gui == 'gtext')
  584. else:
  585. # Shouldn't need this but you never know
  586. fatal(_("Invalid user interface specified - <%s>. "
  587. "Use the --help option to see valid interface names.") % grass_gui)
  588. def gui_startup(wscreen_only = False):
  589. if grass_gui in ('wxpython', 'gtext'):
  590. ret = call([os.getenv('GRASS_PYTHON'), gfile(wxpython_base, "gis_set.py")])
  591. if ret == 0:
  592. pass
  593. elif ret == 1:
  594. # The startup script printed an error message so wait
  595. # for user to read it
  596. message(_("Error in GUI startup. If necessary, please "
  597. "report this error to the GRASS developers.\n"
  598. "Switching to text mode now.\n\n"
  599. "Hit RETURN to continue..."))
  600. sys.stdin.readline()
  601. os.execlp(cmd_name, "-text")
  602. sys.exit(1)
  603. elif ret == 2:
  604. # User wants to exit from GRASS
  605. message(_("Received EXIT message from GUI.\nGRASS is not started. Bye."))
  606. sys.exit(0)
  607. else:
  608. fatal(_("Invalid return code from GUI startup script.\n"
  609. "Please advise GRASS developers of this error."))
  610. def load_gisrc():
  611. global gisdbase, location_name, mapset, location
  612. kv = read_gisrc()
  613. gisdbase = kv.get('GISDBASE')
  614. location_name = kv.get('LOCATION_NAME')
  615. mapset = kv.get('MAPSET')
  616. if not gisdbase or not location_name or not mapset:
  617. fatal(_("Error reading data path information from g.gisenv.\n"
  618. "GISDBASE=%(gisbase)s\n"
  619. "LOCATION_NAME=%(location)s\n"
  620. "MAPSET=%(mapset)s\n\n"
  621. "Check the <%s(file)> file." % \
  622. {'gisbase': gisdbase, 'location': location_name,
  623. 'mapset': mapset, 'file': gisrcrc}))
  624. location = os.path.join(gisdbase, location_name, mapset)
  625. # load environmental variables from grass_env_file
  626. def load_env():
  627. if not os.access(grass_env_file, os.R_OK):
  628. return
  629. for line in readfile(grass_env_file).split(os.linesep):
  630. try:
  631. k, v = map(lambda x: x.strip(), line.strip().split(' ', 1)[1].split('=', 1))
  632. except:
  633. continue
  634. os.environ[k] = v
  635. # Allow for mixed ISIS-GRASS Environment
  636. if os.getenv('ISISROOT'):
  637. isis = os.getenv('ISISROOT')
  638. os.environ['ISIS_LIB'] = isis + os.sep + "lib"
  639. os.environ['ISIS_3RDPARTY'] = isis + os.sep + "3rdParty" + os.sep + "lib"
  640. os.environ['QT_PLUGIN_PATH'] = isis + os.sep + "3rdParty" + os.sep + "plugins"
  641. #os.environ['ISIS3DATA'] = isis + "$ISIS3DATA"
  642. libpath = os.getenv('LD_LIBRARY_PATH', '')
  643. isislibpath = os.getenv('ISIS_LIB')
  644. isis3rdparty = os.getenv('ISIS_3RDPARTY')
  645. os.environ['LD_LIBRARY_PATH'] = libpath + os.pathsep + isislibpath + os.pathsep + isis3rdparty
  646. def set_language():
  647. # This function is used to override system default language and locale
  648. # Such override can be requested only from wxGUI
  649. # An override if user has provided correct environmental variables as
  650. # LC_MESSAGES or LANG is not necessary.
  651. # Unfortunately currently a working solution for Windows is lacking
  652. # thus it always on Vista and XP will print an error.
  653. # See discussion for Windows not following its own documentation and
  654. # not accepting ISO codes as valid locale identifiers http://bugs.python.org/issue10466
  655. import locale
  656. language = 'None' # Such string sometimes is present in wx file
  657. global encoding
  658. # Override value is stored in wxGUI preferences file.
  659. # As it's the only thing required, we'll just grep it out.
  660. try:
  661. fd = open(os.path.join(grass_config_dir, 'wx'), 'r')
  662. except:
  663. # Even if there is no override, we still need to set locale.
  664. pass
  665. else:
  666. for line in fd:
  667. if re.search('^language', line):
  668. line = line.rstrip(' %s' % os.linesep)
  669. language = ''.join(line.split(';')[-1:])
  670. break
  671. fd.close()
  672. if language == 'None' or language == '' or not language:
  673. # Language override is disabled (system language specified)
  674. # As by default program runs with C locale, but users expect to
  675. # have their default locale, we'll just set default locale
  676. try:
  677. locale.setlocale(locale.LC_ALL, '')
  678. except locale.Error as e:
  679. # If we get here, system locale settings are terribly wrong
  680. # There is no point to continue as GRASS/Python will fail
  681. # in some other unpredictable way.
  682. print "System locale is not usable. It indicates misconfigured environment."
  683. print "Reported error message: %s" % e
  684. sys.exit("Fix system locale settings and then try again.")
  685. language, encoding = locale.getdefaultlocale()
  686. if not language:
  687. warning("Default locale settings are missing. GRASS running with C locale.")
  688. return
  689. else:
  690. warning("A language override has been requested. Trying to switch GRASS into '%s'..." % language)
  691. try:
  692. locale.setlocale(locale.LC_ALL, language)
  693. except locale.Error as e:
  694. try:
  695. # Locale lang.encoding might be missing. Let's try
  696. # UTF-8 encoding before giving up as on Linux systems
  697. # lang.UTF-8 locales are more common than legacy
  698. # ISO-8859 ones.
  699. encoding = 'UTF-8'
  700. normalized = locale.normalize('%s.%s' % (language, encoding))
  701. locale.setlocale(locale.LC_ALL, normalized)
  702. except locale.Error as e:
  703. # The last attempt...
  704. try:
  705. encoding = locale.getpreferredencoding()
  706. normalized = locale.normalize('%s.%s' % (language, encoding))
  707. locale.setlocale(locale.LC_ALL, normalized)
  708. except locale.Error as e:
  709. # If we got so far, attempts to set up language and locale have failed
  710. # on this system
  711. sys.stderr.write("Failed to enforce user specified language '%s' with error: '%s'\n" % (language, e))
  712. sys.stderr.write("A LANGUAGE environmental variable has been set.\nPart of messages will be displayed in the requested language.\n")
  713. # Even if setting locale will fail, let's set LANG in a hope,
  714. # that UI will use it GRASS texts will be in selected language,
  715. # system messages (i.e. OK, Cancel etc.) - in system default
  716. # language
  717. os.environ['LANGUAGE'] = language
  718. return
  719. # Set up environment for subprocesses
  720. os.environ['LANGUAGE'] = language
  721. os.environ['LANG'] = language
  722. if encoding:
  723. normalized = locale.normalize('%s.%s' % (language, encoding))
  724. else:
  725. normalized = language
  726. for lc in ('LC_CTYPE', 'LC_MESSAGES', 'LC_TIME', 'LC_COLLATE',
  727. 'LC_MONETARY', 'LC_PAPER', 'LC_NAME', 'LC_ADDRESS',
  728. 'LC_TELEPHONE', 'LC_MEASUREMENT', 'LC_IDENTIFICATION'):
  729. os.environ[lc] = normalized
  730. # Some code in GRASS might not like other decimal separators than .
  731. # Other potential sources for problems are: LC_TIME LC_CTYPE
  732. locale.setlocale(locale.LC_NUMERIC, 'C')
  733. os.environ['LC_NUMERIC'] = 'C'
  734. if os.getenv('LC_ALL'):
  735. del os.environ['LC_ALL'] # Remove LC_ALL to not override LC_NUMERIC
  736. # From now on enforce the new language
  737. if encoding:
  738. gettext.install('grasslibs', os.path.join(gisbase, 'locale'), codeset=encoding)
  739. else:
  740. gettext.install('grasslibs', os.path.join(gisbase, 'locale'), unicode=True)
  741. def check_lock():
  742. global lockfile, force_gislock_removal
  743. if not os.path.exists(location):
  744. fatal(_("Path '%s' doesn't exist") % location)
  745. # Check for concurrent use
  746. lockfile = os.path.join(location, ".gislock")
  747. ret = call([gfile("etc", "lock"), lockfile, "%d" % os.getpid()])
  748. msg = None
  749. if ret == 2:
  750. if not force_gislock_removal:
  751. msg = _("%(user)s is currently running GRASS in selected mapset (" \
  752. "file %(file)s found). Concurrent use not allowed.\nYou can force launching GRASS using -f flag " \
  753. "(note that you need permission for this operation). Have another look in the processor " \
  754. "manager just to be sure..." % {
  755. 'user': user, 'file': lockfile})
  756. else:
  757. try_remove(lockfile)
  758. message(_("%(user)s is currently running GRASS in selected mapset (" \
  759. "file %(file)s found). Forcing to launch GRASS..." % {
  760. 'user': user, 'file': lockfile}))
  761. elif ret != 0:
  762. msg = _("Unable to properly access '%s'.\n"
  763. "Please notify system personel.") % lockfile
  764. if msg:
  765. if grass_gui == "wxpython":
  766. call([os.getenv('GRASS_PYTHON'), gfile(wxpython_base, "gis_set_error.py"), msg])
  767. else:
  768. global remove_lockfile
  769. remove_lockfile = False
  770. fatal(msg)
  771. def make_fontcap():
  772. fc = os.getenv('GRASS_FONT_CAP')
  773. if fc and not os.access(fc, os.R_OK):
  774. message(_("Building user fontcap..."))
  775. call(["g.mkfontcap"])
  776. def check_shell():
  777. global sh, shellname, grass_env_file
  778. # cygwin has many problems with the shell setup
  779. # below, so i hardcoded everything here.
  780. if sys.platform == 'cygwin':
  781. sh = "cygwin"
  782. shellname = "GNU Bash (Cygwin)"
  783. os.environ['SHELL'] = "/usr/bin/bash.exe"
  784. os.environ['OSTYPE'] = "cygwin"
  785. else:
  786. sh = os.path.basename(os.getenv('SHELL'))
  787. if windows and sh:
  788. sh = os.path.splitext(sh)[0]
  789. if sh == "ksh":
  790. shellname = "Korn Shell"
  791. elif sh == "csh":
  792. shellname = "C Shell"
  793. elif sh == "tcsh":
  794. shellname = "TC Shell"
  795. elif sh == "bash":
  796. shellname = "Bash Shell"
  797. elif sh == "sh":
  798. shellname = "Bourne Shell"
  799. elif sh == "zsh":
  800. shellname = "Z Shell"
  801. elif sh == "cmd":
  802. shellname = "Command Shell"
  803. else:
  804. shellname = "shell"
  805. if sh in ['csh', 'tcsh']:
  806. grass_env_file = os.path.join(grass_config_dir, 'cshrc')
  807. elif sh in ['bash', 'msh', 'cygwin', 'sh']:
  808. grass_env_file = os.path.join(grass_config_dir, 'bashrc')
  809. elif sh == 'zsh':
  810. grass_env_file = os.path.join(grass_config_dir, 'zshrc')
  811. elif sh == 'cmd':
  812. grass_env_file = os.path.join(grass_config_dir, 'env.bat')
  813. else:
  814. grass_env_file = os.path.join(grass_config_dir, 'bashrc')
  815. warning(_("Unsupported shell <%(sh)s>: %(env)s") % {'sh': sh,
  816. 'env': grass_env_file})
  817. # check for SHELL
  818. if not os.getenv('SHELL'):
  819. fatal(_("The SHELL variable is not set"))
  820. def check_batch_job():
  821. global batch_job
  822. # hack to process batch jobs:
  823. batch_job = os.getenv('GRASS_BATCH_JOB')
  824. if batch_job:
  825. # defined, but ...
  826. if not os.access(batch_job, os.F_OK):
  827. # wrong file
  828. fatal(_("Job file '%s' has been defined in "
  829. "the 'GRASS_BATCH_JOB' variable but not found. Exiting.\n\n"
  830. "Use 'unset GRASS_BATCH_JOB' to disable batch job processing.") % batch_job)
  831. elif not os.access(batch_job, os.X_OK):
  832. # right file, but ...
  833. fatal(_("Change file permission to 'executable' for '%s'") % batch_job)
  834. else:
  835. message(_("Executing '%s' ...") % batch_job)
  836. grass_gui = "text"
  837. shell = batch_job
  838. bj = Popen(shell, shell=True)
  839. bj.wait()
  840. message(_("Execution of '%s' finished.") % batch_job)
  841. def start_gui():
  842. # Start the chosen GUI but ignore text
  843. if grass_debug:
  844. message(_("GRASS GUI should be <%s>") % grass_gui)
  845. # Check for gui interface
  846. if grass_gui == "wxpython":
  847. Popen([os.getenv('GRASS_PYTHON'), gfile(wxpython_base, "wxgui.py")])
  848. def clear_screen():
  849. if windows:
  850. pass
  851. # TODO: uncomment when PDCurses works.
  852. # cls
  853. else:
  854. if not os.getenv('GRASS_BATCH_JOB') and not grass_debug and not exit_grass:
  855. call(["tput", "clear"])
  856. def show_banner():
  857. sys.stderr.write(r"""
  858. __________ ___ __________ _______________
  859. / ____/ __ \/ | / ___/ ___/ / ____/ _/ ___/
  860. / / __/ /_/ / /| | \__ \\_ \ / / __ / / \__ \
  861. / /_/ / _, _/ ___ |___/ /__/ / / /_/ // / ___/ /
  862. \____/_/ |_/_/ |_/____/____/ \____/___//____/
  863. """)
  864. def say_hello():
  865. sys.stderr.write(_("Welcome to GRASS GIS %s") % grass_version)
  866. if grass_version.endswith('svn'):
  867. try:
  868. filerev = open(os.path.join(gisbase, 'etc', 'VERSIONNUMBER'))
  869. linerev = filerev.readline().rstrip('\n')
  870. filerev.close()
  871. revision = linerev.split(' ')[1]
  872. sys.stderr.write(' (' + revision + ')')
  873. except:
  874. pass
  875. def show_info():
  876. sys.stderr.write(
  877. r"""
  878. %-41shttp://grass.osgeo.org
  879. %-41s%s (%s)
  880. %-41sg.manual -i
  881. %-41sg.version -c
  882. """ % (_("GRASS GIS homepage:"),
  883. _("This version running through:"),
  884. shellname, os.getenv('SHELL'),
  885. _("Help is available with the command:"),
  886. _("See the licence terms with:")))
  887. if grass_gui == 'wxpython':
  888. message("%-41sg.gui wxpython" % _("If required, restart the GUI with:"))
  889. else:
  890. message("%-41sg.gui %s" % (_("Start the GUI with:"), default_gui))
  891. message("%-41sexit" % _("When ready to quit enter:"))
  892. message("")
  893. def csh_startup():
  894. global exit_val
  895. userhome = os.getenv('HOME') # save original home
  896. home = location
  897. os.environ['HOME'] = home
  898. cshrc = os.path.join(home, ".cshrc")
  899. tcshrc = os.path.join(home, ".tcshrc")
  900. try_remove(cshrc)
  901. try_remove(tcshrc)
  902. f = open(cshrc, 'w')
  903. f.write("set home = %s\n" % userhome)
  904. f.write("set history = 3000 savehist = 3000 noclobber ignoreeof\n")
  905. f.write("set histfile = %s\n" % os.path.join(os.getenv('HOME'),
  906. ".history"))
  907. f.write("set prompt = '\\\n")
  908. f.write("Mapset <%s> in Location <%s> \\\n" % (mapset, location_name))
  909. f.write("GRASS GIS %s > '\n" % grass_version)
  910. f.write("set BOGUS=``;unset BOGUS\n")
  911. path = os.path.join(userhome, ".grass.cshrc") # left for backward compatibility
  912. if os.access(path, os.R_OK):
  913. f.write(readfile(path) + '\n')
  914. if os.access(grass_env_file, os.R_OK):
  915. f.write(readfile(grass_env_file) + '\n')
  916. mail_re = re.compile(r"^ *set *mail *= *")
  917. for filename in [".cshrc", ".tcshrc", ".login"]:
  918. path = os.path.join(userhome, filename)
  919. if os.access(path, os.R_OK):
  920. s = readfile(path)
  921. lines = s.splitlines()
  922. for l in lines:
  923. if mail_re.match(l):
  924. f.write(l)
  925. path = os.getenv('PATH').split(':')
  926. f.write("set path = ( %s ) \n" % ' '.join(path))
  927. f.close()
  928. writefile(tcshrc, readfile(cshrc))
  929. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  930. os.environ['HOME'] = userhome
  931. def bash_startup():
  932. global exit_val
  933. # save command history in mapset dir and remember more
  934. os.environ['HISTFILE'] = os.path.join(location, ".bash_history")
  935. if not os.getenv('HISTSIZE') and not os.getenv('HISTFILESIZE'):
  936. os.environ['HISTSIZE'] = "3000"
  937. # instead of changing $HOME, start bash with: --rcfile "$LOCATION/.bashrc" ?
  938. # if so, must care be taken to explicity call .grass.bashrc et al for
  939. # non-interactive bash batch jobs?
  940. userhome = os.getenv('HOME') # save original home
  941. home = location # save .bashrc in $LOCATION
  942. os.environ['HOME'] = home
  943. bashrc = os.path.join(home, ".bashrc")
  944. try_remove(bashrc)
  945. f = open(bashrc, 'w')
  946. f.write("test -r ~/.alias && . ~/.alias\n")
  947. if os.getenv('ISISROOT'):
  948. f.write("PS1='ISIS-GRASS %s (%s):\w > '\n" % (grass_version, location_name))
  949. else:
  950. f.write("PS1='GRASS %s (%s):\w > '\n" % (grass_version, location_name))
  951. f.write(("""grass_prompt() {
  952. LOCATION="`g.gisenv get=GISDBASE,LOCATION_NAME,MAPSET separator='/'`"
  953. if test -d "$LOCATION/grid3/G3D_MASK" && test -f "$LOCATION/cell/MASK" ; then
  954. echo [%s]
  955. elif test -f "$LOCATION/cell/MASK" ; then
  956. echo [%s]
  957. elif test -d "$LOCATION/grid3/G3D_MASK" ; then
  958. echo [%s]
  959. fi
  960. }
  961. PROMPT_COMMAND=grass_prompt\n""" % (_("2D and 3D raster MASKs present"),
  962. _("Raster MASK present"),
  963. _("3D raster MASK present"))).encode(encoding))
  964. # read environmental variables
  965. path = os.path.join(userhome, ".grass.bashrc") # left for backward compatibility
  966. if os.access(path, os.R_OK):
  967. f.write(readfile(path) + '\n')
  968. if os.access(grass_env_file, os.R_OK):
  969. f.write(readfile(grass_env_file) + '\n')
  970. f.write("export PATH=\"%s\"\n" % os.getenv('PATH'))
  971. f.write("export HOME=\"%s\"\n" % userhome) # restore user home path
  972. f.close()
  973. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  974. os.environ['HOME'] = userhome
  975. def default_startup():
  976. global exit_val
  977. if windows:
  978. os.environ['PS1'] = "GRASS %s> " % (grass_version)
  979. # "$ETC/run" doesn't work at all???
  980. exit_val = subprocess.call([os.getenv('SHELL')])
  981. cleanup_dir(os.path.join(location, ".tmp")) # remove GUI session files from .tmp
  982. else:
  983. os.environ['PS1'] = "GRASS %s (%s):\w > " % (grass_version, location_name)
  984. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  985. if exit_val != 0:
  986. fatal(_("Failed to start shell '%s'") % os.getenv('SHELL'))
  987. def done_message():
  988. if batch_job and os.access(batch_job, os.X_OK):
  989. message(_("Batch job '%s' (defined in GRASS_BATCH_JOB variable) was executed.") % batch_job)
  990. message(_("Goodbye from GRASS GIS"))
  991. sys.exit(exit_val)
  992. else:
  993. message(_("Done."))
  994. message("")
  995. message(_("Goodbye from GRASS GIS"))
  996. message("")
  997. def clean_temp():
  998. message(_("Cleaning up temporary files..."))
  999. nul = open(os.devnull, 'w')
  1000. call([gfile("etc", "clean_temp")], stdout=nul, stderr=nul)
  1001. nul.close()
  1002. def grep(string,list):
  1003. expr = re.compile(string)
  1004. return [elem for elem in list if expr.match(elem)]
  1005. def print_params():
  1006. plat = gfile(gisbase, 'include', 'Make', 'Platform.make')
  1007. fileplat = open(plat)
  1008. linesplat = fileplat.readlines()
  1009. fileplat.close()
  1010. params = sys.argv[2:]
  1011. if not params:
  1012. params = ['arch', 'build', 'compiler', 'path', 'revision']
  1013. for arg in params:
  1014. if arg == 'path':
  1015. sys.stdout.write("%s\n" % gisbase)
  1016. elif arg == 'arch':
  1017. val = grep('ARCH',linesplat)
  1018. sys.stdout.write("%s\n" % val[0].split('=')[1].strip())
  1019. elif arg == 'build':
  1020. build = os.path.join(gisbase,'include','grass','confparms.h')
  1021. filebuild = open(build)
  1022. val = filebuild.readline()
  1023. filebuild.close()
  1024. sys.stdout.write("%s\n" % val.strip().strip('"').strip())
  1025. elif arg == 'compiler':
  1026. val = grep('CC',linesplat)
  1027. sys.stdout.write("%s\n" % val[0].split('=')[1].strip())
  1028. elif arg == 'revision':
  1029. rev = os.path.join(gisbase,'include','grass','gis.h')
  1030. filerev = open(rev)
  1031. linesrev = filerev.readlines()
  1032. val = grep('#define GIS_H_VERSION', linesrev)
  1033. filerev.close()
  1034. sys.stdout.write("%s\n" % val[0].split(':')[1].rstrip('$"\n').strip())
  1035. else:
  1036. message(_("Parameter <%s> not supported") % arg)
  1037. def get_username():
  1038. global user
  1039. if windows:
  1040. user = os.getenv('USERNAME')
  1041. if not user:
  1042. user = "user_name"
  1043. else:
  1044. user = os.getenv('USER')
  1045. if not user:
  1046. user = os.getenv('LOGNAME')
  1047. if not user:
  1048. try:
  1049. p = Popen(['whoami'], stdout = subprocess.PIPE)
  1050. s = p.stdout.read()
  1051. p.wait()
  1052. user = s.strip()
  1053. except:
  1054. pass
  1055. if not user:
  1056. user = "user_%d" % os.getuid()
  1057. def parse_cmdline():
  1058. global args, grass_gui, create_new, exit_grass, force_gislock_removal
  1059. args = []
  1060. for i in sys.argv[1:]:
  1061. # Check if the user asked for the version
  1062. if i in ["-v", "--version"]:
  1063. message("GRASS GIS %s" % grass_version)
  1064. message('\n' + readfile(gfile("etc", "license")))
  1065. sys.exit()
  1066. # Check if the user asked for help
  1067. elif i in ["help", "-h", "-help", "--help"]:
  1068. help_message()
  1069. sys.exit()
  1070. # Check if the -text flag was given
  1071. elif i in ["-text", "--text"]:
  1072. grass_gui = 'text'
  1073. # Check if the -gtext flag was given
  1074. elif i in ["-gtext", "--gtext"]:
  1075. grass_gui = 'gtext'
  1076. # Check if the -gui flag was given
  1077. elif i in ["-gui", "--gui"]:
  1078. grass_gui = default_gui
  1079. # Check if the -wxpython flag was given
  1080. elif i in ["-wxpython", "-wx", "--wxpython", "--wx"]:
  1081. grass_gui = 'wxpython'
  1082. # Check if the user wants to create a new mapset
  1083. elif i == "-c":
  1084. create_new = True
  1085. elif i == "-e":
  1086. exit_grass = True
  1087. elif i == "-f":
  1088. force_gislock_removal = True
  1089. elif i == "--config":
  1090. print_params()
  1091. sys.exit()
  1092. else:
  1093. args.append(i)
  1094. ### MAIN script starts here
  1095. # Get the system name
  1096. windows = sys.platform == 'win32'
  1097. cygwin = "cygwin" in sys.platform
  1098. macosx = "darwin" in sys.platform
  1099. ### commented-out: broken winGRASS
  1100. # if 'GISBASE' in os.environ:
  1101. # sys.exit(_("ERROR: GRASS GIS is already running "
  1102. # "(environmental variable GISBASE found)"))
  1103. # Set GISBASE
  1104. os.environ['GISBASE'] = gisbase
  1105. # set HOME
  1106. if windows and not os.getenv('HOME'):
  1107. os.environ['HOME'] = os.path.join(os.getenv('HOMEDRIVE'),
  1108. os.getenv('HOMEPATH'))
  1109. # set SHELL
  1110. if windows:
  1111. if os.getenv('GRASS_SH'):
  1112. os.environ['SHELL'] = os.getenv('GRASS_SH')
  1113. if not os.getenv('SHELL'):
  1114. os.environ['SHELL'] = os.getenv('COMSPEC', 'cmd.exe')
  1115. atexit.register(cleanup)
  1116. # Set default GUI
  1117. default_gui = "wxpython"
  1118. # the following is only meant to be an internal variable for debugging this
  1119. # script. use 'g.gisenv set="DEBUG=[0-5]"' to turn GRASS debug mode on properly
  1120. grass_debug = os.getenv('GRASS_DEBUG')
  1121. # Set GRASS version number for R interface etc (must be an env_var for MS-Windows)
  1122. os.environ['GRASS_VERSION'] = grass_version
  1123. # Set the GIS_LOCK variable to current process id
  1124. gis_lock = str(os.getpid())
  1125. os.environ['GIS_LOCK'] = gis_lock
  1126. if not os.path.exists(grass_config_dir):
  1127. os.mkdir(grass_config_dir)
  1128. # Set the global grassrc file
  1129. batch_job = os.getenv('GRASS_BATCH_JOB')
  1130. if batch_job:
  1131. gisrcrc = os.path.join(grass_config_dir, "rc.%s" % platform.node())
  1132. if not os.access(gisrcrc, os.R_OK):
  1133. gisrcrc = os.path.join(grass_config_dir, "rc")
  1134. else:
  1135. gisrcrc = os.path.join(grass_config_dir, "rc")
  1136. # Set the username and working directory
  1137. get_username()
  1138. # Parse the command-line options
  1139. parse_cmdline()
  1140. if exit_grass and not create_new:
  1141. fatal(_("Flag -e required also flag -c"))
  1142. # Set language
  1143. # This has to be called before any _() function call!
  1144. # Subsequent functions are using _() calls and
  1145. # thus must be called only after Language has been set.
  1146. set_language()
  1147. # Create the temporary directory and session grassrc file
  1148. create_tmp()
  1149. # Create the session grassrc file
  1150. create_gisrc()
  1151. # Set shell (needs to be called before load_env())
  1152. check_shell()
  1153. # Load environmental variables from the file
  1154. load_env()
  1155. # Ensure GUI is set
  1156. read_gui()
  1157. # Set PATH, PYTHONPATH
  1158. set_paths()
  1159. # Set LD_LIBRARY_PATH (etc) to find GRASS shared libraries
  1160. path_prepend(gfile("lib"), ld_library_path_var)
  1161. # Set GRASS_PAGER, GRASS_PYTHON, GRASS_GNUPLOT, GRASS_PROJSHARE
  1162. set_defaults()
  1163. # Set GRASS_HTML_BROWSER
  1164. set_browser()
  1165. #predefine monitor size for certain architectures
  1166. if os.getenv('HOSTTYPE') == 'arm':
  1167. # small monitor on ARM (iPAQ, zaurus... etc)
  1168. os.environ['GRASS_RENDER_HEIGHT'] = "320"
  1169. os.environ['GRASS_RENDER_WIDTH'] = "240"
  1170. # First time user - GISRC is defined in the GRASS script
  1171. if not os.access(gisrc, os.F_OK):
  1172. if grass_gui == 'text' and len(args) == 0:
  1173. fatal(_("Unable to start GRASS. You can:\n"
  1174. " - Launch GRASS with '-gui' switch (`grass71 -gui`)\n"
  1175. " - Create manually GISRC file (%s)\n"
  1176. " - Launch GRASS with path to "
  1177. "the location/mapset as an argument (`grass71 /path/to/location/mapset`)") % gisrcrc)
  1178. grass_intro()
  1179. else:
  1180. clean_temp()
  1181. if create_new:
  1182. message(_("Creating new GRASS GIS location/mapset..."))
  1183. else:
  1184. message(_("Starting GRASS GIS..."))
  1185. # Check that the GUI works
  1186. check_gui()
  1187. # Parsing argument to get LOCATION
  1188. if not args:
  1189. # Try interactive startup
  1190. location = None
  1191. else:
  1192. if create_new:
  1193. if len(args) > 1:
  1194. non_interactive(args[1], args[0])
  1195. else:
  1196. non_interactive(args[0])
  1197. else:
  1198. non_interactive(args[0])
  1199. # User selects LOCATION and MAPSET if not set
  1200. set_data()
  1201. # Set GISDBASE, LOCATION_NAME, MAPSET, LOCATION from $GISRC
  1202. load_gisrc()
  1203. # Check .gislock file
  1204. check_lock()
  1205. # build user fontcap if specified but not present
  1206. make_fontcap()
  1207. # predefine default driver if DB connection not defined
  1208. # is this really needed?? Modules should call this when/if required.
  1209. if not os.access(os.path.join(location, "VAR"), os.F_OK):
  1210. call(['db.connect', '-c', '--quiet'])
  1211. check_batch_job()
  1212. if not batch_job and not exit_grass:
  1213. start_gui()
  1214. clear_screen()
  1215. # Display the version and license info
  1216. if batch_job:
  1217. grass_gui = 'text'
  1218. clear_screen()
  1219. clean_temp()
  1220. try_remove(lockfile)
  1221. sys.exit(0)
  1222. elif exit_grass:
  1223. clean_temp()
  1224. try_remove(lockfile)
  1225. sys.exit(0)
  1226. else:
  1227. show_banner()
  1228. say_hello()
  1229. show_info()
  1230. if grass_gui == "wxpython":
  1231. message(_("Launching <%s> GUI in the background, please wait...") % grass_gui)
  1232. if sh in ['csh', 'tcsh']:
  1233. csh_startup()
  1234. elif sh in ['bash', 'msh', 'cygwin']:
  1235. bash_startup()
  1236. else:
  1237. default_startup()
  1238. clear_screen()
  1239. clean_env()
  1240. clean_temp()
  1241. try_remove(lockfile)
  1242. # Save GISRC
  1243. s = readfile(gisrc)
  1244. writefile(gisrcrc, s)
  1245. cleanup()
  1246. # After this point no more grass modules may be called
  1247. done_message()