grass.py 49 KB

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