grass.py 49 KB

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