grass.py 49 KB

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