grass.py 51 KB

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