grass.py 50 KB

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