grass.py 50 KB

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