grass.py 49 KB

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